ASP.NET MVC使得在Global.asax.cs中创建自定义路由处理程序变得容易:
routes.MapRoute(
"Default",
"{controller}.aspx/{action}/{id}",
new { action = "Index", id = "" }
).RouteHandler = new SubDomainMvcRouteHandler();
Run Code Online (Sandbox Code Playgroud)
这将导致所有请求由指定的自定义RouteHandler处理.对于此特定处理程序:
public class SubDomainMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
return new SubDomainMvcHandler(requestContext);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行任何操作,在这种情况下,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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1279 次 |
| 最近记录: |