我有一个查询字符串,看起来像这样:
" somename1 = 123,属性=占位符% 3 dnothing % 26 anotherid % 3 dsomevalue& somename = somevalue "
,但我希望查询字符串是类似下面的查询字符串,并替换整个查询字符串与更新的一个有没有办法做到这一点没有重定向?
" somename1 = somevalue1&占位符= Nothing& somename2 = somevalue2& somename3 = somevalue3 "
基本需要删除:"QueryString="带空字符串"%3d"带"&"%26" with "="
到目前为止我做的是:
string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
strQueryString = strQueryString.Replace("QueryString=", "");
if (strQueryString.Contains("%26")) strQueryString = strQueryString.Replace("%26", "&");
if (strQueryString.Contains("%3d")) strQueryString = strQueryString.Replace("%3d", "=");
string x = strQueryString;
}
:
// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
if (this.Request.QueryString.ToString().Contains("QueryString="))
{
this.Request.QueryString.ToString().Replace("QueryString=", "");
if (this.Request.QueryString.ToString().Contains("%26")) this.Request.QueryString.ToString().Replace("%26", "&");
if (this.Request.QueryString.ToString().Contains("%3d")) this.Request.QueryString.ToString().Replace("%3d", "=");
string x = this.Request.QueryString.ToString();
}
// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
代码的第二部分没有替换字符,我不知道在删除所有字符或替换它们后如何将查询字符串更改为新的查询字符串。
不支持修改当前请求的查询字符串。使用私有反射来编辑一些内存状态很可能会破坏ASP。NET,因为它假定查询字符串是不可变的。更改查询字符串的唯一方法是发出一个新请求,可以通过重定向,也可以通过执行一种子请求,例如向使用不同查询字符串的相同页面发出新的HTTP请求。
我可以推荐一个不太知名的内置键/值字典,Context.Items.
与切换只读QueryString对象相比,这样可以获得更好的性能,并且它也可以在整个请求中持续,因此您可以在模块,处理程序等之间共享它。
创建string strQueryString = Request.QueryString.ToString();
if (strQueryString.Contains("QueryString="))
{
HttpContext.Current.Items("qs") = strQueryString.Replace("QueryString=", "").Replace("%26", "&").Replace("%3d", "=");
}
使用string x = HttpContext.Current.Items("qs_d").ToString();
旁注:我缩短了你的代码一些,因为没有必要先检查是否包含任何内容,如果是,替换,只是运行替换,它会更快