如何使用c#从asp.net中的querystring中删除项目?

Bar*_*Alp 54 .net c# asp.net query-string

我想从我的网址中删除"语言"查询字符串.我怎样才能做到这一点 ?(使用Asp.net 3.5,c#)

Default.aspx?Agent=10&Language=2
Run Code Online (Sandbox Code Playgroud)

我想删除"语言= 2",但语言将是第一个,中间或最后一个.所以我会有这个

Default.aspx?Agent=20
Run Code Online (Sandbox Code Playgroud)

xcu*_*cud 115

如果它是HttpRequest.QueryString,那么您可以将集合复制到可写集合中并使用它.

NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢道格.接受的答案让我有点困惑.这听起来像提问者正在导致另一个导航,以从查询字符串中获取不需要的参数. (5认同)
  • 这既简单又优雅 - 希望我能碰到几次 (2认同)

Pau*_*nis 46

这是一个简单的方法.不需要反射器.

    public static string GetQueryStringWithOutParameter(string parameter)
    {
        var nameValueCollection = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
        nameValueCollection.Remove(parameter);
        string url = HttpContext.Current.Request.Path + "?" + nameValueCollection;

        return url;
    }
Run Code Online (Sandbox Code Playgroud)

QueryString.ToString()是必需的,因为Request.QueryString集合是只读的.

  • 最简单,最优雅的解决方案。 (2认同)

Bar*_*Alp 36

最后,

hmemcpy的答案完全适合我,感谢其他朋友的回答.

我使用Reflector获取HttpValueCollection并编写以下代码

        var hebe = new HttpValueCollection();
        hebe.Add(HttpUtility.ParseQueryString(Request.Url.Query));

        if (!string.IsNullOrEmpty(hebe["Language"]))
            hebe.Remove("Language");

        Response.Redirect(Request.Url.AbsolutePath + "?" + hebe );
Run Code Online (Sandbox Code Playgroud)

  • 这是正确答案..NET框架具有HTTP实用程序解析查询字符串方法,正是出于此目的.无需从反射器复制代码或使用正则表达式.请求上下文中的查询字符串集合是只读的原因是因为修改它会使上下文与原始请求不准确.解析查询字符串方法只是为您提供一个全新的集合,该集合不依赖于非只读的请求上下文.请你在这里将此标记为正确答案,谢谢. (2认同)

ann*_*ata 26

我个人的偏好是重写查询或在较低点使用namevaluecollection,但有时候业务逻辑不会使这些都非常有用,有时反射确实是你需要的.在这种情况下,您可以暂时关闭readonly标志,如下所示:

// 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);

// remove
this.Request.QueryString.Remove("foo");

// modify
this.Request.QueryString.Set("bar", "123");

// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);
Run Code Online (Sandbox Code Playgroud)


Iga*_*nik 10

我刚才回答了类似的问题.基本上,最好的办法是使用类HttpValueCollection,它的QueryString属性实际上,不幸的是它是在.NET框架内.您可以使用Reflector来抓取它(并将其放入Utils类中).这样您就可以像NameValueCollection那样操纵查询字符串,但是所有的url编码/解码问题都会得到照顾.

HttpValueCollectionextends NameValueCollection,并且有一个构造函数,它接受一个编码的查询字符串(包括&符号和问号),并覆盖一个ToString()方法,以便稍后从底层集合重建查询字符串.