Search code examples
c#asp.netasp.net-mvcasp.net-mvc-routing

Attribute routing with empty parameter


I created the following route in my RouteConfig.cs

        config.Routes.MapHttpRoute(
            name: "CustomFilter",
            routeTemplate: "api/{controller}/{category}/{begin},{pageSize}",
            defaults: new
            {
                category = RouteParameter.Optional,
                begin = RouteParameter.Optional,
                take = RouteParameter.Optional
            }
        );

That is used by the method below:

public  IHttpActionResult GetStudentsByCategory(string category, int begin, int pageSize)
{
..
}

The custom route works fine, unless the category parameter is missing

1. api/students/tech/1,3 (is working)
2. api/students//1,3 (not working)

Is it possible to make the second URL request (without a category parameter) work?


Solution

  • Add one more Route without category, it should be above current one

     config.Routes.MapHttpRoute(
            name: "CustomFilter-without-cat",
            routeTemplate: "api/{controller}/{begin},{pageSize}",
            defaults: new
            {
                begin = RouteParameter.Optional,
                take = RouteParameter.Optional
            }
        );
      config.Routes.MapHttpRoute(
            name: "CustomFilter",
            routeTemplate: "api/{controller}/{category}/{begin},{pageSize}",
            defaults: new
            {
                category = RouteParameter.Optional,
                begin = RouteParameter.Optional,
                take = RouteParameter.Optional
            }
        );