QueryStrings in ASP.NET Core

Programming C# .NET Core ASP.NET

Creating query string manually in code can lead to errors as you have to deal with encoding/decoding strings, ampersand and question marks all by yourself.

Fortunately, ASP.NET Core has a static class QueryHelpers which has a function called AddQueryString that 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);

Example:

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

// multiple Parameters
var queryParams = new Dictionary<string, string>()
{
{"cat", "cpu" },
{"model", "ryzon5" },
{"products","2600,2600x,3200g,3440g,3600,3600x" }
};

// returns /api/product/list?cat=cpu&model=ryzon5&products=2600,2600x,3200g,3440g,3600,3600x
url = QueryHelpers.AddQueryString("/api/product/list", queryParams);

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

var uri = new Uri(context.RedirectUri);
var queryParams = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);

Very handy and quite error proof.