Asp.net-mvc – Use MVC routing to override controller name when presented with specific action

asp.net-mvcasp.net-mvc-4

I'm attempting to specify a route in MVC4 that ignores a controller name if presented with a specific action name. For example.

mysite.com/AnyControllerNameHere/SpecificAction – Would let me specify the controller and action to use while

mysite.com/AnyControllerNameHere/NotSpecificAction – Would take me the the AnyControllerNameHere Controller and NotSpecificAction method like the MVC default.

I've attempted to code something up but it doesn't seem to do what I want. Full route config is just the MVC defaults plus me attempting to do this so…

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

       routes.MapRoute(
            "SpecificAction",
            "{controller}/SpecificAction",
            new { controller = "Home", action = "SpecificAction" }
            );


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

Best Answer

When you write this:

routes.MapRoute(
    "SpecificAction",
    "{controller}/SpecificAction",
    new { controller = "Home", action = "SpecificAction" });

you intend to override the controller. However, the third argument cannot be used to override parameters. It merely provides the defaults for any parameters that aren't already provided by the URL.

So what you need is a route template which doesn't set the controller parameter, so that the default takes effect:

routes.MapRoute(
    name: "SpecificAction",
    url: "{ignored}/SpecificAction",
    defaults: new { controller = "Home", action = "SpecificAction" });
Related Topic