Skip to main content

A neat way to build query string in ASP.NET Core

Creating query string in code can lead to errors as you have to deal with strings, ampersand and question marks. Fortunately, ASP.NET Core has a static class QueryHelpers which has a function called AddQueryString offers a neat way to build query string in ASP.NET Core. The AddQueryString method has 2 definitions. One for creating query string for single parameter and another for multiple parameters.

public static string AddQueryString(string uri, string name, string value);
public static string AddQueryString(string uri, IDictionary<string, string> queryString);

You can use them in the following way.

//returns /api/product/list?foo=bar
string url = QueryHelpers.AddQueryString("/api/product/list", "foo", "bar"); 

//Multiple Parameters
var queryParams = new Dictionary<string, string>()
{
    {"cat", "221" },
    {"gender", "boy" },
    {"age","4,5,6" }
};
//returns /api/product/list?cat=221&gender=boy&age=4,5,6
url = QueryHelpers.AddQueryString("/api/product/list", queryParams);

The above code is clean and easily managed. You don’t have to deal with ampersand and question marks while adding multiple query string parameters in the query string.

Similar to AddQueryString, the class also has ParseQuery function which parse the query string parameters and returns a dictionary of strings. Very handy.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

3 thoughts to “A neat way to build query string in ASP.NET Core”

Leave a Reply

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