Introduction
Creating well-structured query strings for URLs is a frequent task when interacting with web services. While simple in theory, handling details like the correct use of "&" separators and proper URL encoding can be cumbersome.
Streamlined Solutions
Rather than using lengthy, repetitive code, a more efficient and readable method is to employ a utility class designed for this specific purpose. While the standard .NET Framework lacks such a built-in class, several elegant options exist.
Leveraging HttpValueCollection
One approach uses System.Web.HttpUtility.ParseQueryString(string.Empty)
to create a writable HttpValueCollection
, which functions as a NameValueCollection
. Add your key-value pairs, and then call ToString()
to generate the query string:
<code class="language-csharp">NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); queryString.Add("key1", "value1"); queryString.Add("key2", "value2"); return queryString.ToString(); // Returns "key1=value1&key2=value2" (URL-encoded)</code>
QueryHelpers for .NET Core Applications
For .NET Core projects, Microsoft.AspNetCore.WebUtilities.QueryHelpers
provides a simpler solution:
<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>
This method automatically handles URL encoding and seamlessly adds the query string to the base URL.
Selecting the Best Approach
Both HttpValueCollection
and QueryHelpers
offer effective ways to construct query strings. HttpValueCollection
is suitable for traditional ASP.NET applications, while QueryHelpers
is the preferred choice for .NET Core applications.
The above is the detailed content of How Can I Efficiently Build Elegant Query Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!