Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-routing

How to have many optional routes in .Net Core


How can I make the possibility to accept the requests in different orders and with some optional parameters?

https://localhost:44314/api/courses/page=2&pageSize=6&language=test&institution=test&area=test

https://localhost:44314/api/courses/page=2&pageSize=6&institution=test&area=test

https://localhost:44314/api/courses/page=2&pageSize=6&area=test&language=test

I have tried as below:

[HttpGet]
[Route("page={page:int}&pageSize={pageSize:int}&language={language?}&institution={institution?}&area={area?}")]
public async Task<ActionResult<CourseViewModel>> ListCourses(int page, int pageSize, string language="", string institution="", string area="")

And I have the error as:

System.ArgumentException: 'An optional parameter must be at the end of the segment. In the segment 'page={page}&pageSize={pageSize}&language={language?}&institution={institution?}&area={area?}', optional parameter 'language' is followed by '&institution='. Parameter name: routeTemplate'


Solution

  • Remove the route template and the route table will use the parameters of the action for matching the route via query string in the requested URL

    //GET api/courses?page=2&pageSize=6&language=test&institution=test&area=test
    //GET api/courses?page=2&pageSize=6&institution=test&area=test
    //GET api/courses?page=2&pageSize=6&area=test&language=test
    [HttpGet]
    [Route("")]
    public async Task<ActionResult<CourseViewModel>> ListCourses(int page, int pageSize, string language = "", string institution = "", string area = "")
    

    In this case the order does not matter. Once they are present to be matched.