user1987162
user1987162

Reputation:

MVC5 attribute routing equivalent of route.config route

Say I have the following in my route.config

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

            routes.MapMvcAttributeRoutes();

            routes.MapRoute(name: "category", url: "{category}", defaults: new { controller = "Category", action = "Index" });

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

How do I do the equivalent of my category route using a routing attributes?

I have tried the following:

[Route("{action=Index}")]
public class CategoryController : Controller
{
    [Route("{category}")]
    public ActionResult Index(string category)
    {
        return View(category);
    }
}

But this the throws up an error:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

Is it possible or do I need to leave this one in the route.config?

Upvotes: 1

Views: 236

Answers (1)

user1987162
user1987162

Reputation:

It looks like you are currently not able to do the above with attribute routing only as the only ordering I was able to find was to order the action routes within the controller itself:

[Route("{category}", Name = "Category", Order = 1)]

But this won't help with multiple controller types error. Having done a lot more research about Attribute Routing vs Convention Routing, a lot of the blogs and answers I have come across state that it is probably best to use both types together as certain situations may warrant one or the other.

I think in my case as the order of that route and controller are important, then it is best to use conventional routing for it to make sure it comes at the end (but before the default catch all)

Upvotes: 0

Related Questions