I'm trying to learn to create an API using ASP.NET Core Web API. So using VS2022 I created the default Weatherforecast API with Swagger enabled.
The controller's header has
[Route("api/[controller]/[action]")]
[ApiController]
public class WeatherController : ControllerBase
Just for the sake of learning, I added this method:
[HttpGet("{someId}/{someName}/{someDateTime}/someBool")]
public IActionResult Get(int someId, string someName, DateTime someDateTime, bool someBool)
{
return StatusCode(200, $"Value passed: {someId}/{someName}");
}
When I run it the page opens, I see the method in the swagger page, and I click the 'Try It Out' button. I fill in all four parameters, click "Execute", the API fires and my breakpoint in the controller method is caught. All data is passed in.
In the Swagger page, the Request URL shows
https://localhost:7062/api/Users/Get/65974/Jack%20Smith/1954-03-10/someBool?someBool=false
The method returns "Value passed: 65974/Jack Smith", as it should.
Everything looks like it works, but I'm not convinced this is right.
First, when I go into Postman and fill in parameters on the Params tab and run a GET, it converts the URL to
https://localhost:7062/api/Users/Get?someId=65974&someName=Jack Smith&someDateTime=1954年03月10日&someBool=false
which is different than what Swagger shows. And, this fires the parameterless GET method.
What I'm ultimately trying to achieve is to create an API that can have multiple GET and POST methods that accept different parameters.
Just because it fires the controller method doesn't mean it's right. Do I have this all set up correctly?
Thanks
1 Answer 1
What I'm ultimately trying to achieve is to create an API that can have multiple GET and POST methods that accept different parameters. Just because it fires the controller method doesn't mean it's right. Do I have this all set up correctly?
This is related with how route parameter works for the web api in asp.net core.
[HttpGet("{someId}/{someName}/{someDateTime}/someBool")]
This route attribute is just map for the /api/Weather/Get/{someId}/{someName}/{someDateTime}/someBool.
This is the reason why the https://localhost:7062/api/Users/Get?someId=65974&someName=Jack Smith&someDateTime=1954年03月10日&someBool=false
will not match the [HttpGet("{someId}/{someName}/{someDateTime}/someBool")] public IActionResult Get(int someId, string someName, DateTime someDateTime, bool someBool) They are different route which is inside the asp.net core.
It will just map the no parameter, since no route parameter([HttpGet()]) map's url is https://localhost:7062/api/Users/Get.
More details, you could refer to this article.
I suggest you could set all the route parameter instead of the query string by using below attribute .
[HttpGet("{someId}/{someName}/{someDateTime}/{someBool:bool }")]
public IActionResult Get(int someId, string someName, DateTime someDateTime, bool someBool)
{
return StatusCode(200, $"Value passed: {someId}/{someName}");
}