Sam
Sam

Reputation: 30388

Optional INT parameter in Web API Attribute Routing

I'm trying to create an API method in an ASP.NET Core app that may or may not receive an integer input parameter. I have the following code but getting an error with this. What am I doing wrong?

// GET: api/mycontroller/{id}
[HttpGet("id:int?")]
public IActionResult Get(int id = 0)
{
   // Some logic here...
}

Here's the error I'm getting: enter image description here

Upvotes: 0

Views: 2548

Answers (1)

Stephen Byrne
Stephen Byrne

Reputation: 7475

"id:int?" is not a valid route template, it's just a string literal (like as if you expected the Request Url to literally look like http://server/api/MyController/id:int? which is not allowed. Funnily enough, that's only because of the ? character; if you removed that then the literal would be allowed (even though it's useless).

Whereas "{id:int?}" is a proper route template and will work correctly, i.e. the Url will look like http://server/api/MyController/42 or http://myserver/api/MyController/ which will give the default value

So the method should be like this:

// GET: api/mycontroller/{id}
[HttpGet("{id:int?}")]
public IActionResult Get(int id = 0)
{
   // Some logic here...
}

Upvotes: 2

Related Questions