Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple optional parameters web api attribute routing

I am new to attribute routing, and I am not sure if this is even possible.

I have an attribute route, which works fine like this:

[HttpGet]
[Route("GetIssuesByFlag/{flag:int=3}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag)

Now I want to add some extra optional parameters to narrow down my search, so I want to add 2 extra optional parameters.

What I have tried:

[HttpGet]
[Route("GetIssuesByFlag/{flag:int=3?}/{categoryId:int?}/{tagIds?}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag , int? categoryId = null, int?[] tagIds = null)

This works fine if my call is /api/controller/1/2, but fails with 404 when it comes to /api/controller/1.

How can I achieve this?

Edit 1: Nkosi's answer below worked, however an extra modification was needed.

[HttpGet]
[Route("GetIssuesByFlag/{flag:int=3}/{tagIds?}/{categoryId:int?}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag , List<int> tagIds, int? categoryId = null )

The list or array must be second as it is automatically null if no value is provided and cant be marked as optional with = null.

like image 531
Harry Avatar asked Feb 08 '17 13:02

Harry


People also ask

Which is optional element when you define route config in Web API?

Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig. cs under App_Start folder.

Can we have multiple get methods in Web API?

As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.

What is attribute routing in Web API?

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.


1 Answers

{flag:int=3?} is the problem. it is either optional {flag:int?} with the default value in the action or {flag:int=3}.

[HttpGet]
Route("GetIssuesByFlag/{flag:int=3}/{categoryId:int?}/{tagIds?}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag , int? categoryId = null, int?[] tagIds = null)

You currently have 3 optional parameters. when you have just the 1 value routing table wont know which optional parameter you are referring to, hence the 404

like image 162
Nkosi Avatar answered Sep 19 '22 19:09

Nkosi