我知道我能做到
var nv = HttpUtility.ParseQueryString(req.RawUrl);但是有没有办法把它转换回url呢?
var newUrl = HttpUtility.Something("/page", nv);发布于 2010-10-06 01:20:03
只需在NameValueCollection上调用ToString(),就会以name1=value1&name2=value2查询字符串准备好的格式返回名称值对。请注意,NameValueCollection类型实际上并不支持这一点,暗示这一点是有误导性的,但由于实际返回的内部类型,这种行为在这里是有效的,如下所述。
感谢@mjwills指出HttpUtility.ParseQueryString方法实际上返回的是内部HttpValueCollection对象,而不是常规的NameValueCollection (despite the documentation specifying NameValueCollection。在使用ToString()时,HttpValueCollection会自动对查询字符串进行编码,因此不需要编写循环遍历集合并使用UrlEncode方法的例程。已经返回了所需的结果。
有了结果,您就可以将其附加到URL并重定向:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string url = Request.Url.AbsolutePath + "?" + nameValues.ToString();
Response.Redirect(url);目前,使用反射的唯一方式是使用上面所示的ParseQueryString方法(当然,除了HttpValueCollection之外)。这看起来不会改变,因为Connect issue requesting this class be made public已经关闭,状态为“不会修复”。
顺便说一句,您可以调用nameValues上的Add、Set和Remove方法来修改任何查询字符串项,然后再追加它。如果你对see my response to another question感兴趣的话。
发布于 2013-10-27 18:55:32
string q = String.Join("&",
nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));发布于 2016-09-15 10:48:38
创建一个使用两个循环的扩展方法。我更喜欢这种解决方案,因为它是可读的(不需要linq),不需要System.Web.HttpUtility,并且它可以处理重复的键。
public static string ToQueryString(this NameValueCollection nvc)
{
if (nvc == null) return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string key in nvc.Keys)
{
if (string.IsNullOrWhiteSpace(key)) continue;
string[] values = nvc.GetValues(key);
if (values == null) continue;
foreach (string value in values)
{
sb.Append(sb.Length == 0 ? "?" : "&");
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
}
}
return sb.ToString();
}示例
var queryParams = new NameValueCollection()
{
{ "order_id", "0000" },
{ "item_id", "1111" },
{ "item_id", "2222" },
{ null, "skip entry with null key" },
{ "needs escaping", "special chars ? = &" },
{ "skip entry with null value", null }
};
Console.WriteLine(queryParams.ToQueryString());输出
?order_id=0000&item_id=1111&item_id=2222&needs%20escaping=special%20chars%20%3F%20%3D%20%26https://stackoverflow.com/questions/3865975
复制相似问题