Home > database >  .Net 5.0 - In case of multiple attribute routes defined on an action, query parameter always comes a
.Net 5.0 - In case of multiple attribute routes defined on an action, query parameter always comes a

Time:11-19

In .Net 5.0 API, I have an action on which I have applied multiple attribute routes as defined below

[HttpGet, Route("Get/{id?}"), Route("{id}")]
public void Get(long id)
{
   //do something
}

With this routing, the following paths work fine

  1. api/Controller/1
    
  2. api/Controller/Get/1
    

However, if I pass the id as a query parameter, I always get 0 in 'id'.

e.g.

api/Controller/Get?id=1. 

Any idea what might be causing this issue and how it can be fixed?

CodePudding user response:

Just tested using both net 5 and net 6 , VS 2022 and Postman

api/Controller/Get?id=1

it is working properly

I've used this controller, action

[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet, Route("Get/{id?}"), Route("{id}")]
public void Get(long id)
{
   //do something
}
...
}

UPDATE

but if I add [ApiController] attribute then query string id is 0

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase

It seems that ApiController is not supposed to have a query string at all. It doesn't work even if I change route to this

[HttpGet, Route("Get}")]
public void Get(long id)
{
   //do something
}

SUMMARY

If you want to use a query string just remove an [ApiController] attribute if it is possible for your application.

CodePudding user response:

The problem seemed to be with [APIController] attribute along with the [Route] attribute. I set the SuppressInferBindingSourcesForParameters to true and it seemed to have resolved the issue and now all three URL formats work.

services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressInferBindingSourcesForParameters = true;
});
  • Related