How to separate a fixed route from a variable route with Asp.net mvc5

Asked

Viewed 67 times

4

I have a control that manages videos. I’m trying to make these two methods:

[Route("video/categoria/{categoria}")]
public async Task<ActionResult> Index(string categoria)
{


}

[Route("video/categoria/new-movies")]
public async Task<ActionResult> Index()
{


}

When you run the url /video/categoria/new-movies it falls on the route [Route("video/categoria/{categoria}")] putting the value new-movies within the category variable.

I wonder if there’s any way he could land on the other route.

If it does not exist, it is best to treat everything in the same method?

I seek a more technically correct solution to avoid future problems and facilitate maintenance.

1 answer

4


Try reversing the methods:

[Route("video/categoria/new-movies")]
public async Task<ActionResult> Index()
{


}

[Route("video/categoria/{categoria}")]
public async Task<ActionResult> Index(string categoria)
{


}

Alternatively, step one more method, which is setting up routes in the RouteConfig. Precedence always begins with the most specific route. The most generic route must be last because it is solved last.

namespace SeuProjeto
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "NovosFilmes",
                url: "video/categoria/new-movies",
                defaults: new { controller = "Videos", action = "Index" }
            );

            routes.MapRoute(
                name: "Filmes",
                url: "video/categoria/{categoria}",
                defaults: new { controller = "Videos", action = "Index", categoria = UrlParameter.Optional }
            );

            ...
        }
    }
}
  • It worked and I will mark as a response, you could put as a second suggestion the part of how I would set up this specific case, please?

  • Ready. Now it’s complete.

  • Thanks! Still have to wait 5 min to mark the response.

  • Quiet. No rush.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.