Search code examples
.netasp.net-mvcasp.net-mvc-4asp.net-mvc-routing

Change application behaviour based on whole URL


This might sound like a strange one. I'm hoping to have two identical instances of an application behave differently based on the URL used to access them.

I have two instances of the app deployed on IIS, let's call their paths dev.routeone and dev.routetwo. Both instances point to the same source. Now, say I have two actions in my MainController in this project, ActionOne and ActionTwo, linking up to HTML views viewone.cshtml and viewtwo.cshtml respectively.

The routing configuration would be set up something like this (in RegisterRoutes):

routes.MapRoute(
    name: "ActionOne",
    url: "one",
    defaults: new { controller = "MainController", action = "ActionOne" }
);

routes.MapRoute(
    name: "ActionTwo",
    url: "two",
    defaults: new { controller = "MainController", action = "ActionTwo" }
);

With this setup, both IIS instances behave identically:

http://dev.routeone/one -> ActionOne
http://dev.routeone/two -> ActionTwo

http://dev.routetwo/one -> ActionOne
http://dev.routetwo/two -> ActionTwo

I want to have a situation where, using the same source code, the URL would indicate which action is run when a route is entered. Specifically in this case, dev.routeone directing both routes to ActionOne and the opposite with dev.routetwo:

http://dev.routeone/one -> ActionOne
http://dev.routeone/two -> ActionOne

http://dev.routetwo/one -> ActionTwo
http://dev.routetwo/two -> ActionTwo

Or better still, direct appropriately without the configured routes:

http://dev.routeone/ -> ActionOne
http://dev.routetwo/ -> ActionTwo

I'm not sure if this is possible or advisable, but am open to any solutions. Is there a way to 'look back' over the URL which isn't controlled by the application and use that to determine behaviour?


Solution

  • Seeing as I knew the two URLs that were going to be accessing the site, I was able to do this (note the slightly different formatting, as I have since introduced an ID param to the actions):

    var appID = System.Web.Hosting.HostingEnvironment.ApplicationID;
    
    if (appID.Contains("routeone")
    {
        routes.MapRoute(
            name: "ActionOne",
            url: "{id}",
            defaults: new { controller = "MainController", action = "ActionOne", id = UrlParameter.Optional }
        );
    }
    
    if (appID.Contains("routetwo")
    {
        routes.MapRoute(
            name: "ActionTwo",
            url: "{id}",
            defaults: new { controller = "MainController", action = "ActionTwo", id = UrlParameter.Optional }
        );
    }
    

    This format is not dynamic but can be expanded out to deal with more cases of increasing complexity.