如何在ASP.NET MVC中创建自定义路由处理程序?
答案 0 :(得分:6)
ASP.NET MVC可以在Global.asax.cs中轻松创建自定义路由处理程序:
routes.MapRoute(
"Default",
"{controller}.aspx/{action}/{id}",
new { action = "Index", id = "" }
).RouteHandler = new SubDomainMvcRouteHandler();
这将导致所有请求由指定的自定义RouteHandler处理。对于这个特殊的处理程序:
public class SubDomainMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
return new SubDomainMvcHandler(requestContext);
}
}
然后你可以随意做任何事情,在这种情况下,SubDomainMvcHandler从URL抓取子域并将其作为属性传递给控制器:
public class SubDomainMvcHandler : MvcHandler
{
public SubDomainMvcHandler(RequestContext requestContext) : base(requestContext)
{
}
protected override void ProcessRequest(HttpContextBase httpContext)
{
// Identify the subdomain and add it to the route data as the account name
string[] hostNameParts = httpContext.Request.Url.Host.Split('.');
if (hostNameParts.Length == 3 && hostNameParts[0] != "www")
{
RequestContext.RouteData.Values.Add("accountName", hostNameParts[0]);
}
base.ProcessRequest(httpContext);
}
}