.NET 框架中是否有一个类,如果给定一个序列/可枚举的键值对(或其他任何我对这种格式不严格的东西)可以创建如下查询字符串:
?foo=bar&gar=har&print=1
我可以自己完成这项微不足道的任务,但我想我会要求自己免于重新发明轮子。当一行代码可以做到时,为什么所有这些字符串体操?
您可以使用System.Web.HttpUtility.ParseQueryString
来创建一个空的System.Web.HttpValueCollection
,并像使用它一样使用它NameValueCollection
。
例子:
var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
query ["foo"] = "bar";
query ["gar"] = "har";
query ["print"] = "1";
var queryString = query.ToString(); // queryString is 'foo=bar&gar=har&print=1'
There's nothing built in to the .NET framework, as far as I know, though there are a lot of almosts.
System.Web.HttpRequest.QueryString
is a pre-parsed NameValueCollection
, not something that can output a querystring. System.NetHttpWebRequest
expects you to pass a pre-formed URI, and System.UriBuilder
has a Query
property, but again, expects a pre-formed string for the entire query string.
However, running a quick search for "querystringbuilder" shows a couple of implementations for this out in the web that could serve. One such is this one by Brad Vincent, which gives you a simple fluent interface:
//take an existing string and replace the 'id' value if it exists (which it does)
//output : "?id=5678&user=tony"
strQuery = new QueryString("id=1234&user=tony").Add("id", "5678", true).ToString();
而且,虽然不是很优雅,但我在 RestSharp 中找到了一种方法,正如@sasfrog 在对我的问题的评论中所建议的那样。这是方法。
来自 RestSharp-master\RestSharp\Http.cs
private string EncodeParameters()
{
var querystring = new StringBuilder();
foreach (var p in Parameters)
{
if (querystring.Length > 0)
querystring.Append("&");
querystring.AppendFormat("{0}={1}", p.Name.UrlEncode(), p.Value.UrlEncode());
}
return querystring.ToString();
}
再说一次,不是很优雅,也不是我所期待的,但是,嘿,它完成了工作并为我节省了一些打字时间。
我真的在寻找像西欢的答案(标记为正确答案)这样的东西,但这也有效。
.NET Framework 中没有内置任何东西来保留查询参数的顺序,AFAIK。以下帮助器会执行此操作,跳过空值,并将值转换为不变字符串。当与KeyValueList结合使用时,它使构建 URI 变得非常容易。
public static string ToUrlQuery(IEnumerable<KeyValuePair<string, object>> pairs)
{
var q = new StringBuilder();
foreach (var pair in pairs)
if (pair.Value != null) {
if (q.Length > 0) q.Append('&');
q.Append(pair.Key).Append('=').Append(WebUtility.UrlEncode(Convert.ToString(pair.Value, CultureInfo.InvariantCulture)));
}
return q.ToString();
}