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.
There is a big issue with this method. The guys forgot to implement a possiblity to have an array in the query string like this: http://www.some.url/path/to/query?id=1&id=2&id=3
I’m guessing the Uri/UriBuilder classes are available in .NET Core. Couldn’t you just use https://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c/10836145#10836145?
Yes, Uri can be used but you can only pass string type values while calling AddQuery method.