Attribute Routing not working in areas

Viewed 31457

Scenario: I have a Forms area in my ASP.NET MVC 5 site.

I'm trying to redirect to the Details Action which uses a custom route defined using the new Attribute Routing feature.

The RedirectToAction:

return RedirectToAction("Details", new { slug });

The action I'm redirecting to:

[HttpGet]
[Route("forms/{slug}")]
public ActionResult Details(string slug)
{
    var form = FormRepository.Get(slug);

    ...

    return View(model);
}

I would expect a redirect to http://localhost/forms/my-slug but instead the app is redirecting me to http://localhost/Forms/Details?slug=my-slug.

This means that the attribute routing is not working.

How can this be solved?

I have added the routes.MapMvcAttributeRoutes(); line to my RouteConfig:

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

        routes.MapMvcAttributeRoutes();

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

And here's my Application_Start():

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}
2 Answers
Related