Search code examples
c#asp.net-mvcasp.net-mvc-routing

Why does RedirectToRoute("Default") not redirect to the root?


Given these routes:

routes.MapRoute("Test", "test", new { controller = "Test", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}/{id}", 
  new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

If I call RedirectToRoute("Default") from the Index action of the TestController it redirects to /test but I expected it to redirect to /

I checked the result of calling RedirectToRoute("Default") before returning it during a debugging session.

RedirectToRouteResult result = RedirectToRoute("Default");

It has a property RouteName with a value "Default" and a property RouteValues with no elements (Count = 0). I checked using Reflector, and null is passed internally as the RouteValueDictionary.

Again, I would expect that given the defaults for the route defined in my application, it would redirect to Index view on the HomeController.

Why doesn't it redirect to /?


Solution

  • The RouteValueDictionary filled in to the current action is being used to fill in the Controller, Action, ID. This is usually the functionality you want and lets you do things like <%:Html.ActionLink("MyAction")%> without needing to specify your controller in a view.

    To force it to the complete fall back default just use:

    RedirectToRoute("default", null");

    The second argument is for your routevalues and by specifying it you override the preexisting values.

    However I would say the preferred way would be to have a Home route which will not take any parameters. This means your redirects will not need a load of nulls floating around and a call to RedirectToRoute("Home") is also nice and explicit.

    Edit

    This is a really old answer and as a couple of people have mentioned doesn't seem to have been working for them. For what it's worth I now don't use this pattern and explicitly override controller and area when I need to break out. Not only does it apparently work better but when you come back to the code it's good to see explicitly that you're coming out of this context and mean to blank out certain routevalues.

    For the record I have also tended more towards named route based URL generation over convention based generation.