简体   繁体   中英

Can I automatically remove a parameter on querystring with Request.Url.Query?

When I get the querystring with Request.Url.Query I'd like to exclude a parameter (without using replace, or function like these).

So, for example, if I have this querystring :

?ID=1241&IDL=241&HC=1241

I'd like to exclude IDL getting :

?ID=1241&HC=1241

Is this a implemented way or I need to make my own function?

EDIT : I care about the order of my query string values.

It's still string manipulation, but how about something like:

String.Concat("?",
    String.Join("&",
        Request.Url.Query.Substring(1)
            .Split('&')
            .Where(k => !k.StartsWith("IDL="))
            .ToArray() // For .NET versions prior to v4.0
     )
)

Alternatively you could use Request.QueryString to get at a processed collection of query-string parameters.

EDIT: This will leave your parameters in the order they were sent.

Here's a sample ASPX page that outputs a modified query-string (I've tested it in a ASP.NET 3.5 Web-Site):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Import Namespace="System.Linq" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Query String Removal</title>
</head>
<body>
    Modified query-string: <%=
        String.Concat("?",
            String.Join("&",
                Request.Url.Query.Substring(1)
                    .Split('&')
                    .Where(k => !k.StartsWith("IDL="))
                    .ToArray() // For .NET versions prior to v4.0
             )
        )
    %>
</body>
</html>

NOTE: System.Linq has been imported. An exception will be raised if you don't specify a query-string.

I used this which can be called multiple times if you have a list of keys that you want removed from the querystring if they exists:

private string RemoveQueryStringItemWithKeyName(string url, string keyName)
{
    var urlItemRemoved = String.Join("&", url.Split('&').Where(k => !k.StartsWith(keyName + "=")));
    return urlItemRemoved;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM