Search code examples
c#asp.net-web-apiasp.net-coreasp.net-core-2.1

Handle WebApi Core methods with Id as string and int


I have two methods:

    [HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }

As you can see, i want to pass to my API routes like:

https://localhost:44365/Task/1

and

https://localhost:44365/Task/string

But my WebApi project cant handle it. When i pass route like this:

https://localhost:44365/Task/7dd2514618c4-4575b3b6f2e9731edd61

i get an 400 http and this response:

{
"id": [
    "The value '7dd2514618c4-4575b3b6f2e9731edd61' is not valid."
]
}

While debugging, im not hitting any methods (when i pass string instead of int)

My question is, how to verload methods with one parameters with string or int? These methods do diffrent things

EDIT

When i pass something like:

https://localhost:44365/Task/dddd

I still get response with invalid id


Solution

  • You can define parameter type like [HttpGet("{id:int}")]. For more information refer below link.

    https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-constraints

    Your actions should be like below.

        [HttpGet("{id:int}")]
        public IActionResult GetTask([FromRoute] int id)
        {
        }
    
        [HttpGet("{userId}")]
        public IActionResult GetUserTask([FromRoute] string userId)
        {
        }