RedirectToRoute redirects to the current action instead of redirecting to the route specified by the routename

1.3k views Asked by At

Below is my RouteConfig.cs code snippet:

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

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

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

and in Home/Contact I am redirecting to the route named "myroute", which maps to Home/About. Instead of redirecting to Home/About, it is redirecting to the same action (Home/Contact). Below is my HomeController code:

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return RedirectToRoute("myroute");
    }

Why is the redirect to myroute not functioning?

Any help would be appreciated. Thank you.

2

There are 2 answers

0
Mark Slingerland On

You could make it easier. Use Response.Redirect("Home/About") But I don't know if there are any other requirements.

0
NightOwl888 On

When you use RedirectToRoute, Html.RouteLink, Url.RouteUrl, and related methods that allow you to specify a route by name, the name acts like an additional filter. Basically, it means the route can only match the route named "myroute", but you still need to provide controller, action, and any other required route values in order to match that route.

RedirectToRoute("myroute", new { controller = "Home", action = "About" })

Note that @StephenMuecke 's answer provided in a comment will also work, but only from the Home controller. MVC automatically reuses values from the current request when generating URLs if not explicitly provided.

On a side note, this routing configuration is fundamentally broken because you have 2 routes that both accept lengths of 0, 1, 2, and 3 route segments. Basically, while it is possible to generate a URL with myroute, no incoming route can match myroute because Default is configured to always override it. This will likely lead to problems because the route you intended for that path is never matched, which is going to be confusing to maintain when you add more routes.

See Why map special routes first before common routes in asp.net mvc? for the specifics of this problem and possible solutions.