我有以下查询字符串,我想删除或更新部分查询字符串
?language=en-us&issue=5&pageid=18&search=hawaii&search=hawaii
// 这是我需要格式化的
问题是我有重复的搜索键查询字符串。
我尝试了以下代码,但它不起作用
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
? "{0}?{1}".FormatWith(pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
}
FormatWith 生成错误
string' does not contain a definition for 'FormatWith' and no extension method 'FormatWith' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?
工作代码:
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;
}
函数调用
var URL = Request.Url.AbsoluteUri;
var uri = new Uri(Helper.RemoveQueryStringByKey(URL, "search"));
在我的实际逻辑中,我必须检查 QueryStringsearch
是否存在,然后我将其删除并用新的搜索关键字替换它。
您可以按照逻辑应用它,并且第一个不起作用的示例代码是由于FormatWith
我无法修复,所以我使用了Oded
对我有用的解决方案。