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 discussing 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, then 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 in the Routes 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 only place that will 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 the ASP.NET Core Web API Application, if you want to pass anything as a variable, then you need to use curly braces {}, and inside the curly braces, you need to give the name of the parameter your method accepts. 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}")]
        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 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 intentionally, 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}")]
        public string GetEmployeeById(int Id)
        {
            return $"Return Employee Details : {Id}";
        }

        [Route("Employee/Gender/{Gender}/City/{CityId}")]
        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/10, and you 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 nothing but key-value pairs that you need to pass as part of the URL. Again, you can also pass multiple query strings (i.e., multiple key-value pairs) separated by &. Further, the most important point that you need to remember is that before the first query string or after the domain name, you need to use a question mark (?). The question mark (?) in the URL indicates that the query string is 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 code of EmployeeController is given below.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        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 us understand how to pass multiple query strings with an example. When you implement a search functionality in a real-time application, you generally accept multiple search parameters to filter out the data. Let’s say we want employee city, gender, and department to filter out the number of employees to be returned. Then, 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 you need to initialize the parameter with some default value.

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        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, now 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, you want to search the employees by using all three parameters, i.e., Gender, Department, and City. Then, you 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 the order of the query does not matter, i.e., 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. But in our example, we need to map the complex type parameter with the Query string value. So, explicitly, we need to tell ASP.NET Core Framework to map the complex type parameter with the query string parameter by using the FromQuery attribute, shown in the example below. So, modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        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 Microsoft.AspNetCore.Mvc;
namespace RoutingInASPNETCoreWebAPI.Controllers
{
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [Route("Employee/Search")]
        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}";
        }
    }
}

Now, 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, combining route parameters and query strings in routing is a common practice. This approach allows for more flexible and expressive URLs to capture essential path information (through route parameters) and provide additional, optional data (through query strings).

Let’s consider an example where you have an API endpoint to get employee details. Here, we pass the Employee Gender as part of the Route 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?}")]
        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

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

Route Parameters
  • Definition: Route parameters are part of the URL path. They are used to identify a specific resource or a set of resources.
  • Syntax: Specified within the route template by curly braces, e.g., /api/products/{id}.
  • Usage: Ideal for essential information required to fulfill the request, such as an entity’s unique identifier.
  • Behavior: They are a part of the URL’s path. Mandatory by default. If a route parameter is missing, the route won’t match, and the corresponding controller action won’t be called.
  • Binding: Automatically bind to action method parameters with the same name.
  • Example: Accessing a specific product by ID – /api/products/42.
Query Strings
  • Definition: Query strings are appended to the URL and are used to provide additional, often optional, data for the request.
  • Syntax: Begins with a ? followed by key=value pairs, e.g., /api/products?category=electronics.
  • Usage: Suitable for optional data like filtering, sorting, or specifying certain behaviors. Not ideal for identifying resources.
  • Behavior: Not part of the URL path. Optional by default. The API can still process requests without query string parameters.
  • Binding: Bind to action method parameters, typically using the [FromQuery] attribute, although explicit attributes are not always necessary.
  • Example: Filtering products by category – /api/products?category=electronics.
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 *