如何通过密钥从URL有效地删除查询字符串?

如何从Url中删除Key的查询字符串?

我有以下方法工作正常但只是想知道有更好/更短的方式? 或内置的.NET方法,可以更有效地做到这一点?

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

例如,我可以称之为:

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

希望问题很清楚。

谢谢,

这很好用:

 public static string RemoveQueryStringByKey(string url, string key) { var uri = new Uri(url); // this gets all the query string key value pairs as a collection var newQueryString = HttpUtility.ParseQueryString(uri.Query); // this removes the key if exists newQueryString.Remove(key); // this gets the page path from root without QueryString string pagePathWithoutQueryString = uri.GetLeftPart(UriPartial.Path); return newQueryString.Count > 0 ? String.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) : pagePathWithoutQueryString; } 

一个例子:

 RemoveQueryStringByKey("https://www.google.co.uk/search?#hl=en&output=search&sclient=psy-ab&q=cookie", "q"); 

并返回:

 https://www.google.co.uk/#hl=en&output=search&sclient=psy-ab 

我们也可以使用正则表达式来完成它

 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

 var qs = System.Web.HttpUtility.ParseQueryString(queryString); var str = qs.Get(key); 

这个帮助器类也有Set方法。

这个怎么样:

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

我找到了一种不使用正则表达式的方法:

 private string RemoveQueryStringByKey(string sURL, string sKey) { string sOutput = string.Empty; int iQuestion = sURL.IndexOf('?'); if (iQuestion == -1) return (sURL); int iKey = sURL.Substring(iQuestion).IndexOf(sKey) + iQuestion; if (iKey == -1) return (sURL); int iNextAnd = sURL.Substring(iKey).IndexOf('&') + iKey + 1; if (iNextAnd == -1) { sOutput = sURL.Substring(0, iKey - 1); } else { sOutput = sURL.Remove(iKey, iNextAnd - iKey); } return (sOutput); } 

我在最后添加另一个字段时尝试了这个,它也可以正常工作。

我认为最短的方式(我认为在所有情况下产生有效的URL,假设URL有效开始)将使用此正则表达式(其中getRidOf是您要删除的变量名称)和替换是一个零长度字符串"" ):

 (?<=[?&])getRidOf=[^&]*(&|$) 

或者甚至是

 \bgetRidOf=[^&]*(&|$) 

虽然可能不是绝对最漂亮的 URL,但我认为它们都是有效的:

  INPUT OUTPUT ----------- ------------ blah.com/blah.php?getRidOf=d.co&blah=foo blah.com/blah.php?blah=foo blah.com/blah.php?f=0&getRidOf=d.co&blah=foo blah.com/blah.php?f=0&blah=foo blah.com/blah.php?hello=true&getRidOf=d.co blah.com/blah.php?hello=true& blah.com/blah.php?getRidOf=d.co blah.com/blah.php? 

这是一个简单的正则表达式替换:

 Dim RegexObj as Regex = New Regex("(?<=[?&])getRidOf=[^&]*(&|$)") RegexObj.Replace("source.url.com/find.htm?replace=true&getRidOf=PLEASE!!!", "") 

...应该导致字符串:

 "source.url.com/find.htm?replace=true&" 

...这似乎对ASP.Net应用程序有效,而replace确实等于true (不是true&或类似的东西)

如果你有一个不起作用的情况,我会尝试调整它:)

 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 everythingBehindQ = new List(sEverythingBehindQ.Split('&')); foreach (string OneParamPair in everythingBehindQ) { int iIsKeyInThisParamPair = OneParamPair.IndexOf(sKey); if (iIsKeyInThisParamPair != -1) { sToReplace = "&" + OneParamPair; } } sOutput = sURL.Replace(sToReplace, ""); return (sOutput); } 

在删除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"); 

对不起,这有点脏,但应该在旧框架中工作

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

这是我的解决方案:

我添加了一些额外的输入validation。

 public static void TryRemoveQueryStringByKey(ref string url, string key) { if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(key) || Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute) == false) { return false; } try { Uri uri = new Uri(url); // This gets all the query string key value pairs as a collection NameValueCollection queryCollection = HttpUtility.ParseQueryString(uri.Query); string keyValue = queryCollection.Get(key); if (url.IndexOf("&" + key + "=" + keyValue, StringComparison.OrdinalIgnoreCase) >= 0) { url = url.Replace("&" + key + "=" + keyValue, String.Empty); return true; } else if (url.IndexOf("?" + key + "=" + keyValue, StringComparison.OrdinalIgnoreCase) >= 0) { url = url.Replace("?" + key + "=" + keyValue, String.Empty); return true; } else { return false; } } catch { return false; } } 

一些unit testing示例:

 string url1 = "http://www.gmail.com?a=1&cookie=cookieValue" Assert.IsTrue(TryRemoveQueryStringByKey(ref url1,"cookie")); //OUTPUT: "http://www.gmail.com?a=1" string url2 = "http://www.gmail.com?cookie=cookieValue" Assert.IsTrue(TryRemoveQueryStringByKey(ref url2,"cookie")); //OUTPUT: "http://www.gmail.com" string url3 = "http://www.gmail.com?cookie=" Assert.IsTrue(TryRemoveQueryStringByKey(ref url2,"cookie")); //OUTPUT: "http://www.gmail.com" 

System命名空间中有一个非常有用的类叫做UriBuilder ,自.NET 1.1以来一直可用。

 Uri u = new Uri("http://example.com?key1=value1&key2=value2"); UriBuilder b = new UriBuilder(u); b.RemoveQueryItem("key1"); u = b.Uri; 

我在Uri上使用它作为扩展方法,如下所示:

 public static class UriExtensions { public static Uri DropQueryItem(this Uri u, string key) { UriBuilder b = new UriBuilder(u); b.RemoveQueryItem(key); return b.Uri; } } 

这是一个完整的解决方案,适用于指定的> = 0 params,以及任何forms的URL:

  ///  /// Given a URL in any format, return URL with specified query string param removed if it exists ///  public static string StripQueryStringParam(string url, string paramToRemove) { return StripQueryStringParams(url, new List {paramToRemove}); } ///  /// Given a URL in any format, return URL with specified query string params removed if it exists ///  public static string StripQueryStringParams(string url, List 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; } 
 string url = HttpContext.Current.Request.Url.AbsoluteUri; string[] separateURL = url.Split('?'); NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(separateURL[1]); queryString.Remove("param_toremove"); string revisedurl = separateURL[0] + "?" + queryString.ToString();