我有以下querystring&我想删除或更新部分查询字符串
?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"));
在我的实际逻辑中,我必须检查QueryString search
是否存在,如果是,那么我将其删除并将其替换为新的搜索关键字。
您可以按逻辑应用它,&第一个不起作用的示例代码是由FormatWith
引起的,我无法修复,因此我使用Oded
提供的解决方案,对我有用。
答案 0 :(得分:4)
直接使用string.Format
。看起来您复制了代码库中的代码,该代码库定义了您尚未复制的FormatWith
扩展方法(或者未包含其所在的命名空间)。
使用string.Format
:
return newQueryString.Count > 0
? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
如果扩展方法在代码库中,另一个选项是添加using
declaration扩展方法所在的命名空间。
答案 1 :(得分:0)
return newQueryString.Count > 0
? "{0}?{1}".FormatWith(pagePathWithoutQueryString, newQueryString)
: pagePathWithoutQueryString;
string'不包含'FormatWith'的定义,也没有扩展方法'FormatWith'接受类型'string'的第一个参数(你是否缺少using指令或汇编引用?
我认为该错误是自我解释的,您的返回代码中存在错误 string-object中没有FormatWith。
还可以使用Request.QueryString收集QueryStrings,它将返回键和值的集合。 更改此集合,然后使用Response.QueryString重新发送它可能会做你想要的。