如何在 C# 中为 URL 构建查询字符串? [英] How to build a query string for a URL in C#?
问题描述
从代码调用 Web 资源时的一项常见任务是构建查询字符串以包含所有必要的参数.虽然绝不是火箭科学,但您需要注意一些漂亮的细节,例如,如果不是第一个参数,则附加 &
,对参数进行编码等.
A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are some nifty details you need to take care of like, appending an &
if not the first parameter, encoding the parameters etc.
实现它的代码很简单,但有点乏味:
The code to do it is very simple, but a bit tedious:
StringBuilder SB = new StringBuilder();
if (NeedsToAddParameter A)
{
SB.Append("A="); SB.Append(HttpUtility.UrlEncode("TheValueOfA"));
}
if (NeedsToAddParameter B)
{
if (SB.Length>0) SB.Append("&");
SB.Append("B="); SB.Append(HttpUtility.UrlEncode("TheValueOfB")); }
}
这是一项非常常见的任务,人们希望存在一个实用程序类,使其更加优雅和可读.扫描MSDN,没找到—这让我想到了以下问题:
This is such a common task one would expect a utility class to exist that makes it more elegant and readable. Scanning MSDN, I failed to find one—which brings me to the following question:
你所知道的最优雅的清洁方式是什么?
What is the most elegant clean way you know of doing the above?
推荐答案
如果您深入了解 QueryString 属性是一个 NameValueCollection.当我做了类似的事情时,我通常对序列化和反序列化感兴趣,所以我的建议是建立一个 NameValueCollection 然后传递给:
If you look under the hood the QueryString property is a NameValueCollection. When I've done similar things I've usually been interested in serialising AND deserialising so my suggestion is to build a NameValueCollection up and then pass to:
using System.Linq;
using System.Web;
using System.Collections.Specialized;
private string ToQueryString(NameValueCollection nvc)
{
var array = (
from key in nvc.AllKeys
from value in nvc.GetValues(key)
select string.Format(
"{0}={1}",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(value))
).ToArray();
return "?" + string.Join("&", array);
}
我想在 LINQ 中也有一种超级优雅的方法可以做到这一点......
I imagine there's a super elegant way to do this in LINQ too...
这篇关于如何在 C# 中为 URL 构建查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!