C#elegant constructing query string
In Web development, creating query string for the URL is a common task. Although it is simple, it involves details such as adding "&" symbols, coding parameters, and avoiding duplication. This article discusses a elegant and easy to read query string.
Elegant solution
One method is to use the httpvalueCollection class, which can be obtained using system.web.httputility.parsequerystring (string.empty). By adding key value pairs to this set, you can use the Tostring () method to obtain the query string of URL encoding:
<code class="language-csharp">NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); queryString.Add("key1", "value1"); queryString.Add("key2", "value2"); return queryString.ToString(); // 返回 "key1=value1&key2=value2",所有内容都经过URL编码</code>
In .NET CORE, Microsoft.aspnetcore.Webutilities.queryhelpers simplified the construction of the query string:
Conclusion
<code class="language-csharp">const string url = "https://customer-information.azure-api.net/customers/search/taxnbr"; var param = new Dictionary<string, string>() { { "CIKey", "123456789" } }; var newUrl = new Uri(QueryHelpers.AddQueryString(url, param));</code>
The above is the detailed content of How to Elegantly Build Query Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!