0

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

6
  • What error are you getting? Commented Jun 29, 2016 at 21:00
  • Just added the error in the original post. Commented Jun 29, 2016 at 21:03
  • Not overly familiar with asp.net core and don't have a dev. env handy, but I suspect it should be like this: "{id?:int}" whereby you are indicating that id is optional and the type is int. So you are missing the { and } and also the ? is in the wrong place as far as I can tell. Commented Jun 29, 2016 at 21:07
  • According to Microsoft documentation, mine is the correct syntax: asp.net/web-api/overview/web-api-routing-and-actions/… Commented Jun 29, 2016 at 21:13
  • Yes, I see, however the problem is for sure the missing { and }, because I just tested it and it works fine with { and } but without them I see the same error. So it should be "{id:int?}...otherwise "id:int?" is being treated as a literal string, not a route template. Commented Jun 29, 2016 at 21:19

1 Answer 1

2

"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...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.