简体   繁体   English

如何使用 c# 从 asp.net 中的查询字符串中删除项目?

[英]How can I remove item from querystring in asp.net using c#?

I want remove "Language" querystring from my url. How can I do this?我想从我的 url 中删除“语言”查询字符串。我该怎么做? (using Asp.net 3.5, c#) (使用 Asp.net 3.5,c#)

Default.aspx?Agent=10&Language=2

I want to remove "Language=2", but language would be the first,middle or last.我想删除“Language=2”,但语言将是第一个、中间或最后一个。 So I will have this所以我会有这个

Default.aspx?Agent=20

If it's the HttpRequest.QueryString then you can copy the collection into a writable collection and have your way with it.如果它是 HttpRequest.QueryString 则您可以将集合复制到可写集合中并按照自己的方式进行处理。

NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");

Here is a simple way.这里有一个简单的方法。 Reflector is not needed.不需要反射器。

    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;
    }

Here QueryString.ToString() is required because Request.QueryString collection is read only.这里QueryString.ToString()是必需的,因为Request.QueryString集合是只读的。

Finally,最后,

hmemcpy answer was totally for me and thanks to other friends who answered. hmemcpy 的回答完全适合我,并感谢其他回答的朋友。

I grab the HttpValueCollection using Reflector and wrote the following code我使用 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 );

My personal preference here is rewriting the query or working with a namevaluecollection at a lower point, but there are times where the business logic makes neither of those very helpful and sometimes reflection really is what you need.我个人的偏好是重写查询或在较低的点使用 namevaluecollection,但有时业务逻辑使这两种方法都没有太大帮助,有时反射确实是您所需要的。 In those circumstances you can just turn off the readonly flag for a moment like so:在这种情况下,您可以像这样暂时关闭只读标志:

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

I answered a similar question a while ago.不久前我回答了一个类似的问题 Basically, the best way would be to use the class HttpValueCollection , which the QueryString property actually is, unfortunately it is internal in the .NET framework.基本上,最好的方法是使用HttpValueCollection类, QueryString属性实际上就是这个类,不幸的是它在 .NET 框架中是内部的。 You could use Reflector to grab it (and place it into your Utils class).您可以使用 Reflector 来抓取它(并将其放入您的 Utils 类中)。 This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.通过这种方式,您可以像 NameValueCollection 一样操作查询字符串,但所有 url 编码/解码问题都会为您处理。

HttpValueCollection extends NameValueCollection , and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection. HttpValueCollection扩展了NameValueCollection ,并有一个构造函数,它接受一个编码的查询字符串(包括与号和问号),它覆盖了ToString()方法,以便稍后从底层集合重建查询字符串。

Try this ...尝试这个 ...

PropertyInfo isreadonly   =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);    

isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");
  1. Gather your query string by using HttpContext.Request.QueryString .使用HttpContext.Request.QueryString收集您的查询字符串。 It defaults as a NameValueCollection type.它默认为NameValueCollection类型。
  2. Cast it as a string and use System.Web.HttpUtility.ParseQueryString() to parse the query string (which returns a NameValueCollection again).将其转换为字符串并使用System.Web.HttpUtility.ParseQueryString()解析查询字符串(再次返回NameValueCollection )。
  3. You can then use the Remove() function to remove the specific parameter (using the key to reference that parameter to remove).然后,您可以使用Remove()函数删除特定参数(使用键引用要删除的参数)。
  4. Use case the query parameters back to a string and use string.Join() to format the query string as something readable by your URL as valid query parameters.用例查询参数返回一个字符串,并使用string.Join()将查询字符串格式化为您的 URL 可读的内容,作为有效的查询参数。

See below for a working example, where param_to_remove is the parameter you want to remove.请参阅下面的工作示例,其中param_to_remove是您要删除的参数。

Let's say your query parameters are param1=1&param_to_remove=stuff&param2=2 .假设您的查询参数是param1=1&param_to_remove=stuff&param2=2 Run the following lines:运行以下几行:

var queryParams = System.Web.HttpUtility.ParseQueryString(HttpContext.Request.QueryString.ToString());
queryParams.Remove("param_to_remove");
string queryString = string.Join("&", queryParams.Cast<string>().Select(e => e + "=" + queryParams[e]));

Now your query string should be param1=1&param2=2 .现在您的查询字符串应该是param1=1&param2=2

You don't make it clear whether you're trying to modify the Querystring in place in the Request object.您没有明确说明您是否尝试修改 Request 对象中的 Querystring。 Since that property is read-only, I guess we'll assume you just want to mess with the string.由于该属性是只读的,我想我们会假设您只是想弄乱字符串。

... In which case, it's borderline trivial. ...在这种情况下,这是微不足道的。

  • grab the querystring off the Request从请求中获取查询字符串
  • .split() it on '&' .split() 它在 '&'
  • put it back together into a new string, while sniffing for and tossing out anything starting with "language"将它重新组合成一个新的字符串,同时嗅探并丢弃以“语言”开头的任何内容

Get the querystring collection, parse it into a ( name=value pair ) string, excluding the one you want to REMOVE, and name it newQueryString获取querystring集合,解析成( name=value pair )字符串,不包括要REMOVE的字符串,命名为newQueryString

Then call Response.Redirect(known_path?newqueryString) ;然后调用Response.Redirect(known_path?newqueryString) ;

If you have already the Query String as a string, you can also use simple string manipulation:如果您已经将查询字符串作为字符串,您还可以使用简单的字符串操作:

int pos = queryString.ToLower().IndexOf("parameter=");
if (pos >= 0)
{
    int pos_end = queryString.IndexOf("&", pos);
    if (pos_end >= 0)   // there are additional parameters after this one
        queryString = queryString.Substring(0, pos) + queryString.Substring(pos_end + 1);
    else
        if (pos == 0) // this one is the only parameter
            queryString = "";
        else        // this one is the last parameter
            queryString=queryString.Substring(0, pos - 1);
}

well I have a simple solution , but there is a little javascript involve.好吧,我有一个简单的解决方案,但是涉及到一些 javascript。

assuming the Query String is "ok=1"假设查询字符串是“ok=1”

    string url = Request.Url.AbsoluteUri.Replace("&ok=1", "");
   url = Request.Url.AbsoluteUri.Replace("?ok=1", "");
  Response.Write("<script>window.location = '"+url+"';</script>");
string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language";   //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");

https://regexr.com/3i9vj https://regexr.com/3i9vj

您可能想要使用正则表达式来查找要从查询字符串中删除的参数,然后将其删除并将浏览器重定向到具有新查询字符串的同一文件。

Yes, there are no classes built into .NET to edit query strings.是的,.NET 中没有内置类来编辑查询字符串。 You'll have to either use Regex or some other method of altering the string itself.您必须使用 Regex 或其他一些更改字符串本身的方法。

Parse Querystring into a NameValueCollection.将 Querystring 解析为 NameValueCollection。 Remove an item.删除一个项目。 And use the toString to convert it back to a querystring.并使用 toString 将其转换回查询字符串。

using System.Collections.Specialized;

NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");

var queryString = '?'+ filteredQueryString.ToString();

ASP .NET Core (native, don't have to reference any additional libraries) ASP .NET 核心(原生,不必引用任何额外的库)

Within an ASP .NET Core Controller you would have access to an instance of Request在 ASP .NET Core Controller 中,您可以访问 Request 的实例

  • Request.Query is a query collection representing the query parameters, cast it to a list Request.Query 是表示查询参数的查询集合,将其转换为列表

  • From which you can filter and remove the params you want您可以从中过滤和删除所需的参数

  • Use QueryString.Create, which can take the list you just filtered as an input & generate a query string directly使用QueryString.Create,可以将刚刚筛选的列表作为输入,直接生成查询字符串

     var removeTheseParams = new List<string> {"removeMe1", "removeMe2"}.AsReadOnly(); var filteredQueryParams = Request.Query.ToList().Where(filterKvp =>.removeTheseParams.Contains(filterKvp;Key)). var filteredQueryString = QueryString.Create(queryParamsFilteredList);ToString(): //Example. Console?Writeline(filteredQueryString) will give you "?q1=v1&q2=v2"

Optional Part Below : Can also encode those values if they are unsafe, so in addition to the Where() above UrlEncode the query parameter keys and values using a Select() as shown below:下面的可选部分:如果它们不安全,也可以对这些值进行编码,因此除了上面的 Where() 之外,使用 Select() 对查询参数键和值进行 UrlEncode 编码,如下所示:

     //Optional
     .Select(cleanKvp => new KeyValuePair<string, string?>(UrlEncoder.Default.Encode(cleanKvp.Key),UrlEncoder.Default.Encode(cleanKvp.Value)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用C#从asp.net的querystring中一一删除ID? - How can i remove ids one by one from querystring in asp.net using c#? asp.net:如何从下拉列表中删除项目? - asp.net: How can I remove an item from a dropdownlist? 从下拉列表 ASP.NET MVC 5 和 C# 中删除项目 - Remove item from dropdownlist ASP.NET MVC 5 and C# C#ASP.NET QueryString解析器 - C# ASP.NET QueryString parser 使用ASP.NET(C#)在不使用QueryString的情况下将变量从页面传递到页面 - Passing Variable from page to page using ASP.NET (C#) without using QueryString 如何使用C#给出指向标签的链接并将查询字符串传递给asp.net中的另一个页面 - how to give link to the label and pass querystring to another page in asp.net using c# 如何对从C#控制台应用程序使用表单身份验证的ASP.NET WebAPI进行身份验证? - How can I authenticate to an ASP.NET WebAPI that is using Forms Authentication From a C# Console Application? 如何从文本框的值添加查询字符串? ASP .NET C# - how to add querystring from value of textbox? ASP .NET c# 如何从asp.net c#中的url中删除“.aspx”? - How to remove “.aspx” from url in asp.net c#? 如何在asp.net中将我的URL从QueryString重写为基于文件夹的URL - How can I rewrite my URL in asp.net from QueryString to folder based URL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM