Asp.net mvc route based on subdomain

Total Post:134

Points:940
 2465  View(s)
Ratings:
Rate this:

Is it possible to have an ASP.NET MVC route that uses subdomain information to determine its route? For example.

·         user1.domain.com goes to one place

·         user2.domain.com goes to another?

Or, can I make it so both of these go to the same controller/action with a username parameter?

  1. Post:194

    Points:1396
    Re: Asp.net mvc route based on subdomain

    You can do it by creating a new route and adding it to the routes collection in RegisterRoutes in your global.asax. Below is a very simple example of a custom Route.

    public class ExampleRoute : RouteBase
            {
     
                public override RouteData GetRouteData(HttpContextBase httpContext)
                {
                    var url = httpContext.Request.Headers["HOST"];
                    var index = url.IndexOf(".");
     
                    if (index < 0)
                        return null;
     
                    var subDomain = url.Substring(0, index);
     
                    if (subDomain == "user1")
                    {
                        var routeData = new RouteData(this, new MvcRouteHandler());
                        routeData.Values.Add("controller", "User1");                    routeData.Values.Add("action", "Index");
     
                        return routeData;
                    }
     
                    if (subDomain == "user2")
                    {
                        var routeData = new RouteData(this, new MvcRouteHandler());
                        routeData.Values.Add("controller", "User2");
                        routeData.Values.Add("action", "Index");
     
                        return routeData;
                    }
     
                    return null;
                }
     
                public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
                {
                    return null;
                }
            }

      Modified On Apr-05-2018 07:06:16 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!