您需要创建自定义路由。只需继承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();
}
}