Route Parameters and Query Strings in Routing

Route Parameters and Query Strings in ASP.NET Core Web API Routing

In this article, I will discuss Working with Route Parameters and Query Strings in ASP.NET Core Web API Routing with Examples. Please read our previous article on Routing in ASP.NET Core Web API Applications. We will also work with the same example we created in our previous article.

Working with Route Parameters in ASP.NET Core Web API Routing:

When working with real-time restful services, we need to deal with dynamic values like getting order details by ID, getting employee details by ID, getting books by author, etc. Let us see how we can handle the Route Data using Attribute Routing in the ASP.NET Core Web API Application.

For example, we have multiple employees and want to fetch one employee’s details by its ID. Then, how can we get the ID values? The URL is the best place to give us the ID value. So, we need to define one parameter to take the ID value within the method signature, as shown in the image below.

Variables and Query Strings in ASP.NET Core Web API Routing .

In ASP.NET Core Web API Application, if you want to pass anything as part of the URL Path (Route data), then we need to use curly braces {} and inside the curly braces, we need to give the name of the parameter same name as the method parameter. In our example, the GetEmployeeById method takes the Id parameter, so we need to pass the Id within the curly braces of the Route attribute, as shown in the image below.

Working with Variables in ASP.NET Core Web API Routing

So, modify the EmployeeController class as shown below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/{Id}")]
        [HttpGet]
        public string GetEmployeeById(int Id)
        {
            return $"Return Employee Details : {Id}";
        }
    }
}

Now, you can access the GetEmployeeById action method using the URL: /Employee/100 (instead of 100, you can pass any dynamic value, i.e., the actual Employee ID, which information you want to retrieve). So run the above application, access the /Employee/100 endpoint, and you should get the output as shown in the image below.

Variables in ASP.NET Core Web API Routing

This is how we pass dynamic values using routing.

Passing Multiple Dynamic Values in ASP.NET Core Web API Routing:

Let us understand how to pass multiple dynamic values using the Route attribute. Now we need to fetch all the employees by Gender and City. Here, we want the Gender to be Male or Female, i.e., as a string value, and we want the City ID value, i.e., an integer value. So, we will create one action method that takes two parameters, one of which is Gender and the other one is CityId, as shown in the image below.

Passing Multiple dynamic Values in ASP.NET Core Web API Routing

Now we want to access the above GetEmployeesByGenderAndCity method using the URL: /Employee/Gender/Male/City/10

Here, Male and 10 are the dynamic values. So, we need to decorate the GetEmployeesByGenderAndCity method with the Route Attribute, as shown in the image below. Here, we are passing the Gender and CityId parameters in curly braces.

Multiple dynamic Values in ASP.NET Core Web API Routing

So, modify the EmployeeController class as shown below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/{Id}")]
        [HttpGet]
        public string GetEmployeeById(int Id)
        {
            return $"Return Employee Details : {Id}";
        }

        [Route("Employee/Gender/{Gender}/City/{CityId}")]
        [HttpGet]
        public string GetEmployeesByGenderAndCity(string Gender, int CityId)
        {
            return $"Return Employees with Gender : {Gender}, City: {CityId}";
        }
    }
}

Now run the application and navigate to the URL Employee/Gender/Male/City/10You should get the message as expected, as shown in the image below.

how to work with variables and Query Strings in ASP.NET Core Web API Routing

This is how you can pass multiple dynamic values in your routing.

Working with Query Strings in ASP.NET Core Web API Routing:

Let us understand how to work with Query Strings in ASP.NET Core Web API Routing. Query Strings are key-value pairs that we need to pass as part of the URL. Again, we can also pass multiple query strings (i.e., multiple key-value pairs) separated by &.

The most important point is that you need to use a question mark (?) before the first query string or after the domain name. The question mark (?) in the URL indicates that the query string has started.

Let us understand the query string with an example. Now, we need to search employees by department name. But we don’t want the department name to be part of the Route Attribute. Then how can we do this? We can do this by using the query string. So, let us create a method named SearchEmployee with one parameter called Department, as shown in the image below. Further notice: we have not included that parameter in the Route Attribute.

Working with Query Strings in ASP.NET Core Web API Routing

The complete EmployeeController code is given below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        [HttpGet]
        public string SearchEmployees(string Department)
        {
            return $"Return Employees with Department : {Department}";
        }
    }
}

The URL to access the above action method is /Employee/Search, but how can we pass the value for the Department parameter? The answer is the query string. So, what we need to do is append ?Department=IT to the end of the URL (/Employee/Search?Department=IT) and press enter as shown in the image below.

Query Strings in ASP.NET Core Web API

How do you pass Multiple Query Strings in ASP.NET Core Web API?

Let’s understand how to pass multiple query strings with an example. When we implement search functionality in a real-time application, we generally accept multiple search parameters to filter out the data.

Let’s say we want to filter employees by city, gender, and department. In that case, our action method accepts three parameters. So, modify the SearchEmployees method of the Employee Controller class as shown below. If you want to make any query string parameter optional, then you need to use ? or initialize the parameter with some default value.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        [HttpGet]
        public string SearchEmployees(string? Department, string? Gender, string? City = null)
        {
            return $"Return Employees with Department : {Department}, Gender : {Gender}, City : {City}";
        }
    }
}

With the above changes in place, run the application. Let’s say we want to filter the employees by Gender only. Then, you can only pass the Gender query string in the URL (/Employee/Search?Gender=Male), as shown in the image below.

How to pass Multiple Query Strings in ASP.NET Core Web API?

Now, you want to search the employees by Gender and Department. Then, you can pass two query strings in the URL (/Employee/Search?Gender=Male&Department=HR), as shown in the image below.

Query Strings in ASP.NET Core Web API Routing

Now, we want to search for employees using all three parameters: Gender, Department, and City. Then, we can pass the query strings in the URL (/Employee/Search?City=London&Gender=Male&Department=HR), as shown in the image below. The point is that you need to remember that the order of the query does not matter; you can pass the query strings in any order.

how to work with Query Strings in ASP.NET Core Web API Routing

Using Query Strings with Model Binding in ASP.NET Core Web API

You can also use a model to bind query string parameters. So, let us create a model called EmployeeSearch.cs and then copy and paste the following code.

namespace RoutingInASPNETCoreWebAPI
{
    public class EmployeeSearch
    {
        public string? Department { get; set; }
        public string? Gender { get; set; }
        public string? City { get; set; }
    }
}
Modify the EmployeeController:

By default, the simple type parameters are mapped with query string, and complex type parameters are mapped with the request body. However, we want to map the complex type parameter with the Query string values in our example. So, explicitly, we need to tell the ASP.NET Core Framework to map the complex type parameter with the query string parameter by using the FromQuery attribute, as shown in the example below. 

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        [HttpGet]
        public string SearchEmployees([FromQuery]EmployeeSearch employeeSearch)
        {
            return $"Return Employees with Department : {employeeSearch.Department}, Gender : {employeeSearch.Gender}, City : {employeeSearch.City}";
        }
    }
}

Now, search the employees by Gender and Department as query strings in the URL (/Employee/Search?Gender=Male&Department=HR), and you should get the following result.

Query Strings in ASP.NET Core Web API Routing

Accessing Query Strings Directly from HttpContext

Sometimes, you might want to access the query string directly within the controller action method. For a better understanding, please modify the EmployeeController as follows. Here, we access the Gender and Department query string values directly from the action method using the HttpContext.Request.Query collection.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        [HttpGet]
        public string SearchEmployees()
        {
            var Department = HttpContext.Request.Query["department"].ToString();
            var Gender = HttpContext.Request.Query["gender"].ToString();
            return $"Return Employees with Department : {Department}, Gender : {Gender}";
        }
    }
}

With the above changes in place, run the application and search the employees by Gender and Department as query strings in the URL (/Employee/Search?Gender=Male&Department=HR), and you should get the following result.

Query Strings in ASP.NET Core Web API Routing

Routing with both Route Parameter and Query String in ASP.NET Core Web API

In ASP.NET Core Web API, it is also possible to combine route parameters and query strings in routing. Let’s consider an example where we have an API endpoint to get employee details. Here, we pass the Employee Gender as part of the Route Data and CityId and Department as part of the Query Strings. So, modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        // Using both route parameter and query string
        [Route("Employee/{Gender?}")]
        [HttpGet]
        public string GetEmployeesByGenderAndCity(string? Gender, int? CityId, string? Department)
        {
            return $"Return Employees with Gender: {Gender}, City: {CityId}, Department: {Department}";
        }
    }
}

Now, with the above changes in place, run the application and search the employees by Gender as Route Data, Department, and CityId as query strings in the URL (/Employee/Male?Department=HR&CityId=100), and you should get the following result.

Routing with both Route Parameter and Query String in ASP.NET Core Web API

Query String vs Route Parameter in ASP.NET Core Web API Routing

Understanding the distinction between query strings and route parameters in ASP.NET Core Web API is essential for effective API design. Both are used to pass information to the server, but they serve different purposes and have different implications for API usability and functionality.

Route Parameters

Route parameters are part of the URL path. They identify a specific resource or a set of resources. They are ideal for sending mandatory information required to fulfill the request, such as an entity’s unique identifier. If a route parameter is missing, the route won’t match, and the corresponding controller action won’t be called.

Query Strings

Query strings are appended to the URL and provide additional, often optional, data for the request. They begin with a ? followed by key-value pairs, e.g., /API/products?category=electronics. They are suitable for optional data like filtering, sorting, or specifying certain behaviors, but they are not ideal for identifying resources. Bind to action method parameters, typically using the [FromQuery] attribute.

Key Differences
  • Position in URL: Route parameters are part of the URL path, while query strings are appended to the URL.
  • Optionality: Route parameters are generally mandatory, while query strings are optional.
  • Use Cases: Route parameters identify specific resources (e.g., a particular product). Query strings are used for additional request information (e.g., filters, search terms).

This is how query strings work in ASP.NET Core Web API Routing. In the next article, I will discuss Setting Multiple URLs for a Single Resource in ASP.NET Core Web API Application using Routing. In this article, I explain how to work with Route Parameters and Query Strings in ASP.NET Core Web API Routing with Examples. I hope you enjoy Route Parameters and Query Strings in the ASP.NET Core Web API Routing article.

Leave a Reply

Your email address will not be published. Required fields are marked *