以NameValueCollection 修改URL中的查询参数

本文参考于:http://www.c-sharpcorner.com/Blogs/9421/add-remove-or-modify-the-query-string-value-in-url-in-asp-n.aspx

示例效果:

针对原URL: http://www.cnblogs.com/freeliver54?KeyB=ValueB&KeyD=ValueD&KeyC=ValueC

对查询参数

进行新增 KeyA=ValueA

进行修改 KeyB=ValueB ->KeyB=ValueB2

进行删除 KeyD

得到新的URL: http://www.cnblogs.com/freeliver54?KeyB=ValueU&KeyC=ValueC&KeyA=ValueA

相关代码如下:

private string UpdateQueryString() {

    string urlOld = "http://www.cnblogs.com/freeliver54?KeyB=ValueB&KeyD=ValueD&KeyC=ValueC";
//System.Web.HttpUtility.UrlDecode(returnUrl, Encoding.Unicode);
string urlNew = ""; if (urlOld.Contains("?"))
{
string[] separateURL = urlOld.Split('?'); System.Collections.Specialized.NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(separateURL[]); queryString.Remove("KeyD");
queryString.Add("KeyA", "ValueA");
queryString["KeyB"] = "ValueB2"; urlNew = separateURL[] + "?" + queryString.ToString();
}
else
{
urlNew = urlOld + "?KeyA=ValueA" ;
} return urlNew;
}
05-04 05:47