iJade
iJade

Reputation: 23791

Adding custom created route into route collection in Global.asax

I'm quite new to asp.net mvc, so this could be quite trivial. I'm trying to do asp.net mvc routing based on subdomain. I have been following this StackOverFlow post. I created the class as said but I'm pretty confused about how to add it to routes collection in Global.asax. What i'm trying to accomplish is routing both user1.exmaple.com and user2.example.com to the same controller with parameters. Here is the custom created 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"); //Goes to the User1Controller class
            routeData.Values.Add("action", "Index"); //Goes to the Index action on the User1Controller

            return routeData;
        }

        if (subDomain == "user2")
        {
            var routeData = new RouteData(this, new MvcRouteHandler());
            routeData.Values.Add("controller", "User2"); //Goes to the User2Controller class
            routeData.Values.Add("action", "Index"); //Goes to the Index action on the User2Controller

            return routeData;
        }

        return null;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        //Implement your formating Url formating here
        return null;
    }
}

Upvotes: 0

Views: 1835

Answers (1)

Sergey
Sergey

Reputation: 3213

You would usually add your custom route in App_Data\RouteConfig.cs file

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Add(new ExampleRoute());
    }
}

And make sure it's called in your Global.asax Application_Start()

    protected void Application_Start()
    {
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

Upvotes: 1

Related Questions