Daniel Powell
Daniel Powell

Reputation: 8293

supporting multi-tenant routes in mvc

I'm experimenting setting up a multi-tenant solution in asp.net mvc 4 wherein you are able to specify tenant specific overrides to certain controllers if they require different functionality.

I'd like to have routes that are like

/{Controller}/{Action}/{Id}/
/{Tenant}/{Controller}/{Action}/{Id}

If the tenant isn't specified it should just match the first route.

I have tried

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

            routes.MapRoute(
                name: "Tenant",
                url: "{tenant}/{controller}/{action}/{id}",
                defaults: new { tenant = "", controller = "Home", action = "Index", id = UrlParameter.Optional });

This works correctly for

If I switch the routes around then the tenant route works but the base one does not.

What am I missing here, is it possible to achieve this?

Note, I'd prefer to not have to specify a dummy tenant string in the route as I'll have to translate that back later on in a few places where I need to resolve tenant specific information.

Upvotes: 2

Views: 1856

Answers (1)

Siyamand
Siyamand

Reputation: 54

You can use the library I wrote here. This lib allows you to define an alternative route, if the routes conflict. You must define the routes as follows:

var firstRoute = routes.MapReplaceableRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });    

var secoundRoute = routes.MapRoute(
            name: "Tenant",
            url: "{tenant}/{controller}/{action}/{id}",
            defaults: new { tenant = "", controller = "Home", action = "Index", id = 
UrlParameter.Optional }, lookupParameters: new string[] {"tenant"}, lookupService: new LookupService());

firstRoute.AlternativeRoute  = secondRoute;

For lookupService, you just need an empty implementation of the IRouteValueLookupService.

Upvotes: 2

Related Questions