Home >Backend Development >C++ >How Can I Elegantly Build Query Strings in C#?

How Can I Elegantly Build Query Strings in C#?

DDD
DDDOriginal
2025-01-29 23:46:11289browse

How Can I Elegantly Build Query Strings in C#?

Streamlining Query String Creation in C#

Constructing query strings for URLs is a frequent task in web development. Manual string manipulation is error-prone and cumbersome. This article explores cleaner, more efficient methods.

Leveraging HttpValueCollection

The HttpValueCollection class provides a structured approach. Add key-value pairs, and the ToString() method generates a URL-encoded query string:

<code class="language-csharp">NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);

queryString.Add("key1", "value1");
queryString.Add("key2", "value2");

string query = queryString.ToString();</code>

Utilizing Microsoft.AspNetCore.WebUtilities.QueryHelpers (for .NET Core)

In .NET Core applications, the QueryHelpers class offers a more concise solution:

<code class="language-csharp">Dictionary<string, string> parameters = new Dictionary<string, string>() { { "CIKey", "123456789" } };

Uri newUrl = new Uri(QueryHelpers.AddQueryString("https://customer-information.azure-api.net/customers/search/taxnbr", parameters));</code>

These methods offer significant improvements in code clarity and maintainability compared to manual string concatenation, reducing the risk of errors and improving overall development efficiency.

The above is the detailed content of How Can I Elegantly Build Query Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn