Search code examples
c#routesasp.net-core-webapiasp.net-core-6.0

ASP.NET Core Web API : route by query parameter


I am coming from a heavy Java/Spring background and trying to transition some knowledge over to ASP.NET Core 6.

In Spring, on a RestController, I am able to route the request based on the presence of a query parameter.

So a HttpRequest with the uri: /students?firstName=Kevin can be routed to a different controller method than a HttpRequest with the uri: /students.

In ASP.NET Core 6, I am unable to determine if the equivalent is possible after working through some examples and reading the documentation for Web API.

Here is what I am trying to achieve, is this possible using two methods and routing configuration that will discern which controller method to invoke based on the query parameter?

 [ApiController]
 [Route("Students")]
 public class StudentProfileController : ControllerBase
 {
    [HttpGet] //Route here when no parameters provided
    public async Task<ActionResult<IEnumerable<Student>>> GetStudentAsync()
    {
        /* Code omitted */
    }

    [HttpGet] //Route here when firstName query param provided
    public async Task<ActionResult<IEnumerable<Student>>> SearchStudentAsync([FromQuery] string firstName)
    {
        /* Code omitted */
    }
 }

Solution

  • You are trying to differentiate API calls using query params. this is not the way to do this. if you want to separate the calls you should probably use path params instead.

    Read more about Routing in ASP.NET Core - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-6.0