How to efficiently remove a query string by Key fr

2019-01-22 06:20发布

How to remove a query string by Key from a Url?

I have the below method which works fine but just wondering is there any better/shorter way? or a built-in .NET method which can do it more efficiently?

 public static string RemoveQueryStringByKey(string url, string key)
        {
            var indexOfQuestionMark = url.IndexOf("?");
            if (indexOfQuestionMark == -1)
            {
                return url;
            }

            var result = url.Substring(0, indexOfQuestionMark);
            var queryStrings = url.Substring(indexOfQuestionMark + 1);
            var queryStringParts = queryStrings.Split(new [] {'&'});
            var isFirstAdded = false;

            for (int index = 0; index <queryStringParts.Length; index++)
            {
                var keyValue = queryStringParts[index].Split(new char[] { '=' });
                if (keyValue[0] == key)
                {
                    continue;
                }

                if (!isFirstAdded)
                {
                    result += "?";
                    isFirstAdded = true;
                }
                else
                {
                    result += "&";
                }

                result += queryStringParts[index];
            }

            return result;
        }

For example I can call it like:

  Console.WriteLine(RemoveQueryStringByKey(@"http://www.domain.com/uk_pa/PostDetail.aspx?hello=hi&xpid=4578", "xpid"));

Hope the question is clear.

Thanks,

13条回答
Bombasti
2楼-- · 2019-01-22 06:55

Here's a full solution that works with >= 0 params specified, and any form of URL:

    /// <summary>
    /// Given a URL in any format, return URL with specified query string param removed if it exists
    /// </summary>
    public static string StripQueryStringParam(string url, string paramToRemove)
    {
        return StripQueryStringParams(url, new List<string> {paramToRemove});
    }

    /// <summary>
    /// Given a URL in any format, return URL with specified query string params removed if it exists
    /// </summary>
    public static string StripQueryStringParams(string url, List<string> paramsToRemove)
    {
        if (paramsToRemove == null || !paramsToRemove.Any()) return url;

        var splitUrl = url.Split('?');
        if (splitUrl.Length == 1) return url;

        var urlFirstPart = splitUrl[0];
        var urlSecondPart = splitUrl[1];

        // Even though in most cases # isn't available to context,
        // we may be passing it in explicitly for helper urls
        var secondPartSplit = urlSecondPart.Split('#');
        var querystring = secondPartSplit[0];
        var hashUrlPart = string.Empty;
        if (secondPartSplit.Length > 1)
        {
            hashUrlPart = "#" + secondPartSplit[1];
        }
        var nvc = HttpUtility.ParseQueryString(querystring);
        if (!nvc.HasKeys()) return url;

        // Remove any matches
        foreach (var key in nvc.AllKeys)
        {
            if (paramsToRemove.Contains(key))
            {
                nvc.Remove(key);
            }
        }

        if (!nvc.HasKeys()) return urlFirstPart;
        return urlFirstPart + 
               "?" + string.Join("&", nvc.AllKeys.Select(c => c.ToString() + "=" + nvc[c.ToString()])) + 
               hashUrlPart;
    }
查看更多
太酷不给撩
3楼-- · 2019-01-22 06:56

We can also do it using regex

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);   //this will not work for javascript, for javascript you can do following
string finalQS = Regex.Replace(queryString, regex, "");

//javascript(following is not js syntex, just want to give idea how we can able do it in js)
string regex1 = string.Format("(&{0}=[^&\s]+)",parameterToRemove);
string regex2 = string.Format("(\?{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex1, "").Replace(queryString, regex2, "");

https://regexr.com/3i9vj

查看更多
地球回转人心会变
4楼-- · 2019-01-22 06:59

Below code before deleting your QueryString.

 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("yourKey");
查看更多
够拽才男人
5楼-- · 2019-01-22 07:00

How about this:

        string RemoveQueryStringByKey(string url, string key)
    {
        string ret = string.Empty;

        int index = url.IndexOf(key);
        if (index > -1)
        {
            string post = string.Empty;

            // Find end of key's value
            int endIndex = url.IndexOf('&', index);
            if (endIndex != -1) // Last query string value?
            {
                post = url.Substring(endIndex, url.Length - endIndex);
            }

            // Decrement for ? or & character
            --index;
            ret = url.Substring(0, index) + post;
        }

        return ret;
    }
查看更多
可以哭但决不认输i
6楼-- · 2019-01-22 07:00

Sorry this is a bit dirty but should work in older framework

public String RemoveQueryString( String rawUrl  , String keyName)
{
    var currentURL_Split =  rawUrl.Split('&').ToList();
    currentURL_Split = currentURL_Split.Where(o => !o.ToLower().StartsWith(keyName.ToLower()+"=")).ToList();
    String New_RemovedKey = String.Join("&", currentURL_Split.ToArray()); 
    New_RemovedKey = New_RemovedKey.Replace("&&", "&");
    return New_RemovedKey;
}
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-22 07:03
public static string RemoveQueryStringByKey(string sURL, string sKey)
    {
        string sOutput = string.Empty;
        string sToReplace = string.Empty;

        int iFindTheKey = sURL.IndexOf(sKey);
        if (iFindTheKey == -1) return (sURL);

        int iQuestion = sURL.IndexOf('?');
        if (iQuestion == -1) return (sURL);

        string sEverythingBehindQ = sURL.Substring(iQuestion);
        List<string> everythingBehindQ = new List<string>(sEverythingBehindQ.Split('&'));
        foreach (string OneParamPair in everythingBehindQ)
        {
            int iIsKeyInThisParamPair = OneParamPair.IndexOf(sKey);
            if (iIsKeyInThisParamPair != -1)
            {
                sToReplace = "&" + OneParamPair;
            }
        }

        sOutput = sURL.Replace(sToReplace, "");
        return (sOutput);
    }
查看更多
登录 后发表回答