2

I have 2 routes:

  1. college/{courseId}/{classId}
  2. college/{courseId}

But sometime when I try to input the 1st url type like college/course1/class2, it go to the 2nd action.

Can I fix route configuration to do it exactly? Here is my code:

[Route("college/{courseId}/{classId}")]
public void ActionResult example1(string courseId, string classId) {
    return View();
}
[Route("college/{courseId}")]
public void ActionResult example2(string courseId) {
    return View();
}

RouteConfig.cs file:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        AreaRegistration.RegisterAllAreas();
        routes.MapMvcAttributeRoutes();

        //Default
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
Andrei
  • 42,814
  • 35
  • 154
  • 218
tanbaobu
  • 43
  • 2
  • 6

2 Answers2

1

This may be helpful to you.

https://www.nuget.org/packages/routedebugger/

It will show you what routes are matched.

I suspect that they both are matched but are added in the incorrect order.

It may be as simple as inverting the order in which they are adding or making them more specific. ( making the params required)

Spaceman
  • 1,319
  • 13
  • 42
0

I recommend you to define only one route and have only one action with an optional parameter:

[Route("college/{courseId}/{classId?}")]
public void ActionResult example1(string courseId, string classId) {
    // Do classId null check if necessary
    return View();
}

Please notice, there is a question mark after classId parameter in route definition.

Andrei
  • 42,814
  • 35
  • 154
  • 218