ASP.NET MVC, Manipulating URL Structure

前端 未结 1 1792
执笔经年
执笔经年 2021-01-07 04:11

How do I create a custom route handler in ASP.NET MVC?

相关标签:
1条回答
  • 2021-01-07 04:28

    ASP.NET MVC makes it easy to create a custom route handler in the Global.asax.cs:

        routes.MapRoute(
            "Default",
            "{controller}.aspx/{action}/{id}",
            new { action = "Index", id = "" }
          ).RouteHandler = new SubDomainMvcRouteHandler();
    

    This will result in all requests being handled by the custom RouteHandler specified. For this particular handler:

        public class SubDomainMvcRouteHandler : MvcRouteHandler
        {
            protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
            {
                return new SubDomainMvcHandler(requestContext);
            }
        }
    

    You can then do whatever you want, in this case the SubDomainMvcHandler grabs the subdomain from the URL and passes it through to the controller as a property:

        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);
            }
        }
    
    0 讨论(0)
提交回复
热议问题