1
votes

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?

1
Since your "category" route will always override the "default" route when the URL has 1 segment passed (i.e. /somewhere), your routing is most likely misconfigured to begin with. For example /Home won't access your HomeController and Index method, it will instead go to CategoryController and Index method. Please specify exactly what URLs should go where in your question, because it is currently unclear.NightOwl888
@NightOwl888 my home route works fine as it is defined in the attributes which is configured before the category (in the register routes section) I guess my question really boils down to are you able to set the order of the routing instructions using attribute routing so that I can set my category route in the place it is declared if I were to use conventional routinguser1987162

1 Answers

0
votes

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)