Search code examples
c#asp.netroutesasp.net-mvc-5

If I set default route and attribute routing to same controller in mvc5 then conventional routing is not working


Controller

    [HttpGet]
[Route("find-a-doctor")]
public ActionResult FindADoctor()
{
    ViewData["sList"] = specialities ;
    return View();
}

Route.Config

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}",
        defaults: new { controller = "UserPanelFinADoctor", action = "FindADoctor" },
         namespaces: new string[] { "xyz.Controllers" }
    );
}

This is the result when I debug code. It says "The resource cannot be found"


Solution

  • I resarched about it , and found this on microsot docs.

    Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed. Actions that define attribute routes cannot be reached through the conventional routes and vice-versa. Any route attribute on the controller makes all actions in the controller attribute routed.

    So in your example .Since you have registered the route to your action under attribute based routing. Convention routing wont work. Either of the one should be used, not both.

    Link to article - https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#mixed-routing-attribute-routing-vs-conventional-routing