In this article, we are going to learn how to read values from query strings in ASP.NET Core.

In web development, the capability to read and utilize values from the query string holds significant importance. It is crucial to adeptly interpret the parameters transmitted through the URL, enabling the extraction of valuable information.

To download the source code for this article, you can visit our GitHub repository.

Let’s start. 

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Understanding the Fundamentals of Query Strings

First, let’s understand the basics. The URI specification, RFC-3986, refers to the URL part after the question mark symbol (?). The query string consists of key-value pairs separated by ampersands (&).

If we check this URL: "https://example.com/search?q=aspnetcore&category=programming", the query string q has the value of aspnetcore, and the category query string has the value of programming. Developers use query strings to transfer data from one page to another or provide additional information to a server.

How to Read Scalar Values?

Let’s discuss how to read scalar values of various data types from a query string:

[HttpGet(template:"/v1",Name = "GetQueryStringsAsScalarValues")]
public IActionResult GetFullNameFromScalarValues([FromQuery] string firstName, [FromQuery] string lastName)
{
    return Ok(new {FullName = $"{firstName} {lastName}"});
}

This GET action method accepts two query string parameters, namely firstName and lastName. Each parameter utilizes the [FromQuery] attribute, indicating that it retrieves its value from the corresponding query string parameter in the URL.

We can inspect the URL as well:

curl -X 'GET' 'http://localhost:5188/v1?firstName=John&lastName=Doe' -H 'accept: */*'

How to Read Array Values?

Let’s continue expanding our knowledge by learning to retrieve multiple values from the query string. This can be useful, for example, when we need to fetch product information by their IDs for specific situations. We can pass the various IDs and their values in the query string to do this.

First, let’s check the sample URL endpoint:

curl -X 'GET' 'http://localhost:5188/v2?ids=1&ids=2&ids=3' -H 'accept: */*'.

By utilizing the ASPNET Core model binding through the [FromQuery] attribute, the controller action method can effectively interpret multiple query strings as an integer array. To gain further clarity, let’s analyze a code snippet:

[HttpGet(template:"/v2",Name = "GetMultipleQueryStringsAsArray")]
public IActionResult GetProductsByIds([FromQuery] int[] ids)
{
    return Ok(new {ProductIds=ids});
}

Here, we have a GET action method that expects a query string parameter named ids in the URL. The values of this parameter are bound to the ids array, and the action method returns the Ok response with a JSON object containing the product IDs.

The [FromQuery] attribute is applied to the ids parameter, indicating that we bind values from the corresponding query string parameter in the URL. The Swagger UI understands this and generates a dynamic user interface:

Dynamic-Swagger-UI

How to Read Object Values?

After discussing scalar and array values, let’s extract multiple values from query strings and serialize them into an object. To better understand this, let’s take a look at an example code:

[HttpGet("/v3", Name = "GetMultipleQueryStringsAsObject")]
public IActionResult GetFullNameFromObject([FromQuery] Person queryStringParameters)
{
    return Ok(new {FullName =$"{queryStringParameters.FirstName} {queryStringParameters.LastName}"});
}

public record Person(string FirstName, string LastName);

In this GET action method, we expect query string parameters for FirstName and LastName. We bind these parameters to the Person object and the action method returns the Ok response. The [FromQuery] attribute is applied to the queryStringParameters parameter, indicating that its values should be bound from the corresponding query string parameters in the URL.

Let’s check again the endpoint URL for our action:

curl -X 'GET' 'http://localhost:5188/v3?FirstName=John&LastName=Doe' -H 'accept: */*' .

 In the pagination article, we also use the same technique to map query strings to an object.  

Conclusion

In this article, we explored the significance of Query Strings in web development and the different methods to read values from query strings through model binding using the [FromQuery] attribute in ASPNET Core. To maintain the security of web applications, it is essential to sanitize query string values as a best practice.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!