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

How to Elegantly Build Query Strings in C#?

Mary-Kate Olsen
Release: 2025-01-29 23:51:13
Original
118 people have browsed it

How to Elegantly Build Query Strings in C#?

C#elegant constructing query string

Introduction

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:

.NET core options

<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>
Copy after login

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>
Copy after login
By using HTTPVALUECOLLECTION or Queryhelpers, developers can elegantly and efficiently build a URL query string to ensure correct encoding and parameter processing. This method enhances the readability and maintenance of code in the web development project.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template