Richiban
Richiban

Reputation: 5930

Is it possible to set a global RoutePrefix for an entire MVC application?

I have an MVC site that we are using just to host our new checkout process. There is a rewrite rule in our ARR server in place so that any requests for https://www.oursite.com/checkout go to this new application instead of the legacy site.

This means that every request to the new application starts with /checkout which leaves us with the slightly unsatisfactory situation of having every controller in the site decorated with [RoutePrefix("checkout")].

Is there a way that I can set a global route prefix that automatically applies to all controllers in the application? We don't have a universal base controller that we own to put an attribute on. The only options I could think of are to go back to the old fashioned routing:

routes.MapRoute(
            "Default",
            "checkout/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = "" }
        );

I'd much prefer to use Attribute Routing, so I want to call something like routes.MapMvcAttributeRoutes(globalPrefix: "checkout");

How can I accomplish this?

Upvotes: 2

Views: 882

Answers (1)

Richiban
Richiban

Reputation: 5930

I found out a way to do it, not sure if it's best practice but it seems to work just fine. I noticed that the MapMvcAttributeRoutes method can take an IDirectRouteProvider as argument.

It took a bit of guesswork but I was able to write a class that derives from the framework's DefaultDirectRouteProvider and overrides the GetRoutePrefix method:

public class CheckoutPrefixRouteProvider : DefaultDirectRouteProvider
{
    protected override string GetRoutePrefix(ControllerDescriptor controllerDescriptor)
    {
        return "checkout/" + base.GetRoutePrefix(controllerDescriptor);
    }
}

I can then use this new class as follows:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes(new CheckoutPrefixRouteProvider());
    }
}

Upvotes: 5

Related Questions