Skip to main content
 首页 » 编程设计

c#之如何在 asp.net 中删除或更新部分查询字符串

2024年02月20日22insus

我有以下查询字符串,我想删除或更新部分查询字符串

?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 提供的解决方案这对我有用。

请您参考如下方法:

直接使用string.Format。看起来您是从定义了 FormatWith 扩展方法的代码库中复制了代码,但您并未复制(或未包含它所在的命名空间)。

使用string.Format:

return newQueryString.Count > 0 
    ? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString) 
    : pagePathWithoutQueryString; 

如果扩展方法在代码库中,另一种选择是添加 using declaration使用扩展方法所在的命名空间。