Home > front end >  .Net Core API - Route Parameters in Query String not working
.Net Core API - Route Parameters in Query String not working

Time:09-02

We are in the process of upgrading our Web API to .Net Core. The API is an Employees API with Employee Search and GET endpoints as below:

GET /employees/{id}
GET /employees

For the Get endpoint, currently the both the below calls works:

https://example.com/employees/001
https://example.com/employees/{id}?id=001

After upgrading the code to .Net Core 6.0, only the below call work:

https://example.com/employees/001

The other call with id in the query string does not work. Is there a way to get both the calls working in .Net Core

CodePudding user response:

This is all how you define your routes. If you put the parameter in the route, like /employees/001, it will look for that path to determine which function to hit. So for instance I setup 2 routes that call 2 functions:

    [Route("Stuff/{id}")]
    public IActionResult StuffWithIDInPath(int id)
    {
        ViewData["idVal"] = id;
        return View("SomeStuff");
    }

    [Route("Stuff")]
    public IActionResult StuffWithIDInQS(int id)
    {
        ViewData["idVal"] = id;
        return View("SomeStuff");
    }

The first route is hit when I go to something/stuff/37

Response to parameter in route

And the second function does not have the parameter in the route, but it is also a parameter to the function, so it knows to look for it if it shows up:

Response with parameter in QS

But perhaps you want one function to handle both scenarios, and you can do that two if you just define the routes correctly for the same function.

    [Route("Stuff/{id}")]
    [Route("Stuff")]
    public IActionResult StuffWithIDEitherPlace(int id)
    {
        ViewData["idVal"] = id;
        return View("SomeStuff");
    }

In that case, either URL will go to that function, handling parameters in the route or as a querystring.

CodePudding user response:

your action route attribute should have id as an optional parameter

     [HttpGet("~/employees/{id?}")]
    public IActionResult Get(int? id)

or if a controller is Employees

 public class Employees : ApiController
..........
    [HttpGet("id?}")]
    public IActionResult Get(int? id)
  • Related