有没有可能有一个ASP。NET MVC路由,使用子域信息来确定它的路由?例如:

user1.domain。例子只有一个 user2.domain。例子指向另一个?

或者,我可以让这两个都去到相同的控制器/动作与用户名参数?


当前回答

这不是我的工作,但我必须把它加到这个答案上。

这里有一个解决这个问题的好办法。martin Balliauw编写了创建DomainRoute类的代码,该类可以与正常的路由使用非常相似。

http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx

示例使用如下所示……

routes.Add("DomainRoute", new DomainRoute( 
    "{customer}.example.com", // Domain with parameters 
    "{action}/{id}",    // URL with parameters 
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults 
))

;

其他回答

这不是我的工作,但我必须把它加到这个答案上。

这里有一个解决这个问题的好办法。martin Balliauw编写了创建DomainRoute类的代码,该类可以与正常的路由使用非常相似。

http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx

示例使用如下所示……

routes.Add("DomainRoute", new DomainRoute( 
    "{customer}.example.com", // Domain with parameters 
    "{action}/{id}",    // URL with parameters 
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults 
))

;

我创建了子域路由库,您可以创建这样的路由。它目前正在为。net Core 1.1和。net Framework 4.6.1工作,但将在不久的将来进行更新。它是这样工作的: 1)在Startup.cs中映射子域路由

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var hostnames = new[] { "localhost:54575" };

    app.UseMvc(routes =>
    {
        routes.MapSubdomainRoute(
            hostnames,
            "SubdomainRoute",
            "{username}",
            "{controller}/{action}",
            new { controller = "Home", action = "Index" });
    )};

2)控制器/ HomeController.cs

public IActionResult Index(string username)
{
    //code
}

3)该库还将允许您生成url和表单。代码:

@Html.ActionLink("User home", "Index", "Home" new { username = "user1" }, null)

将生成<a href="http://user1。localhost: 54575 / Home /指数”> < / >用户家里 生成的URL还取决于当前主机位置和模式。 你也可以为BeginForm和UrlHelper使用html帮助。如果你喜欢,你也可以使用新功能称为标签助手(FormTagHelper, AnchorTagHelper) 该库还没有任何文档,但有一些测试和示例项目,所以请随意探索。

是的,但是你必须创建你自己的路由处理器。

通常情况下,路由不知道域,因为应用程序可以部署到任何域,路由不会关心这种或那种方式。但在你的情况下,你想要基于域的控制器和动作,所以你必须创建一个自定义路由,它可以感知域。

几个月前,我开发了一个属性,将方法或控制器限制在特定的域。

它很容易使用:

[IsDomain("localhost","example.com","www.example.com","*.t1.example.com")]
[HttpGet("RestrictedByHost")]
public IActionResult Test(){}

也可以直接应用到控制器上。

public class IsDomainAttribute : Attribute, Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
{

    public IsDomainAttribute(params string[]  domains)
    {
        Domains = domains;
    }

    public string[] Domains { get; }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var host = context.HttpContext.Request.Host.Host;
        if (Domains.Contains(host))
            return;
        if (Domains.Any(d => d.EndsWith("*"))
                && Domains.Any(d => host.StartsWith(d.Substring(0, d.Length - 1))))
            return;
        if (Domains.Any(d => d.StartsWith("*"))
                && Domains.Any(d => host.EndsWith(d.Substring(1))))
            return;

        context.Result = new Microsoft.AspNetCore.Mvc.NotFoundResult();//.ChallengeResult
    }
}

限制: 你可能不能在不同的过滤器的不同方法上有两个相同的路由 我的意思是下面可能会抛出重复路由的异常:

[IsDomain("test1.example.com")]
[HttpGet("/Test")]
public IActionResult Test1(){}

[IsDomain("test2.example.com")]
[HttpGet("/Test")]
public IActionResult Test2(){}

在ASP。NET Core,主机可以通过Request.Host.Host获得。如果您希望允许通过查询参数覆盖主机,首先检查Request.Query。

要使主机查询参数传播到新的基于路由的url,将以下代码添加到app.UseMvc路由配置中:

routes.Routes.Add(new HostPropagationRouter(routes.DefaultHandler));

然后像这样定义HostPropagationRouter:

/// <summary>
/// A router that propagates the request's "host" query parameter to the response.
/// </summary>
class HostPropagationRouter : IRouter
{
    readonly IRouter router;

    public HostPropagationRouter(IRouter router)
    {
        this.router = router;
    }

    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        if (context.HttpContext.Request.Query.TryGetValue("host", out var host))
            context.Values["host"] = host;
        return router.GetVirtualPath(context);
    }

    public Task RouteAsync(RouteContext context) => router.RouteAsync(context);
}