0

我在 IIS 上有许多指向同一个 ASP.NET MVC 应用程序的主机名。

www.domain.com
www.domain.co.uk
www.domain.net
...

当我设置如下地图路线时,如何获得顶级域(例如“.com”)?

Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

    ' MapRoute takes the following parameters, in order:
    ' (1) Route name
    ' (2) URL with parameters
    ' (3) Parameter defaults
    routes.MapRoute( _
        "Default", _
        "{controller}/{action}/{id}", _
        New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
    )

End Sub
4

1 回答 1

2

您需要创建自定义路由。只需继承Route、覆盖GetRouteData和包含用于 TLD 的路由信息​​。

http://msdn.microsoft.com/en-us/library/system.web.routing.route.getroutedata.aspx

例子

路线:

public class RouteWithTld : Route
{
    public RouteWithTld(string url, IRouteHandler routeHandler) : base(url, routeHandler)
    {
    }

    public RouteWithTld(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
    {
    }

    public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler)
    {
    }

    public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler)
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var baseData = base.GetRouteData(httpContext);

        int pos = httpContext.Request.Url.Host.LastIndexOf('.');
        string tld;
        if (pos == -1)
        {
            if (httpContext.Request.Url.Host == "localhost")
                tld = "com";
            else
            {
                throw new InvalidOperationException("You need to handle this case.");
            }
        }
        else
            tld = httpContext.Request.Url.Host.Substring(pos + 1);

        baseData.Values.Add("tld", tld);

        return baseData;
    }
}

在 global.asax 中映射它:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    /*routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
     * */

    var defaults =
        new RouteValueDictionary(new {controller = "Home", action = "Index", id = UrlParameter.Optional});
    routes.Add(new RouteWithTld("{controller}/{action}/{id}", defaults, new MvcRouteHandler()));

}

并访问控制器中的参数:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC. TLD: " + RouteData.Values["tld"];

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}
于 2012-11-28T14:52:35.400 回答