欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net下URL处理两个小工具方法

程序员文章站 2022-06-20 14:49:03
有的时候我们要操作一个url地址中查询参数,为了不破坏url的原有结构,我们一般不能直接在url的后面加&query=value,特别是我们的url中有多个参数时,这种处理...
有的时候我们要操作一个url地址中查询参数,为了不破坏url的原有结构,我们一般不能直接在url的后面加&query=value,特别是我们的url中有多个参数时,这种处理更麻烦。
下面两个小方法就是专门用来为一个url添加一个查询参数或删除一个查询参数,这两个方法隐藏了原url有无参数,是不是原来就有这个参数,有没有fragment(#anchor)这些细节和处理
/**//// <summary>
/// add a query to an url.
/// if the url has not any query,then append the query key and value to it.
/// if the url has some queries, then check it if exists the query key already,replace the value, or append the key and value
/// if the url has any fragment, append fragments to the url end.
/// </summary>
public static string safeaddquerytourl(string key,string value,string url)
{
int fragpos = url.lastindexof("#");
string fragment = string.empty;
if(fragpos > -1)
{
fragment = url.substring(fragpos);
url = url.substring(0,fragpos);
}
int querystart = url.indexof("?");
if(querystart < 0)
{
url +="?"+key+"="+value;
}
else
{
regex reg = new regex(@"(?<=[&\?])"+key+@"=[^\s]*",regexoptions.compiled);
if(reg.ismatch(url))
url = reg.replace(url,key+"="+value);
else
url += "&"+key+"="+value;
}
return url+fragment;
}
/**//// <summary>
/// remove a query from url
/// </summary>
/// <param name="key"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string saferemovequeryfromurl(string key,string url)
{
regex reg = new regex(@"[&\?]"+key+@"=[^\s]*&?",regexoptions.compiled);
return reg.replace(url,new matchevaluator(putawaygarbagefromurl));
}
private static string putawaygarbagefromurl(match match)
{
string value = match.value;
if(value.endswith("&"))
return value.substring(0,1);
else
return string.empty;
}

测试:
string s = "http://www.cnblogs.com/?a=1&b=2&c=3#tag";
wl(saferemovequeryfromurl("a",s));
wl(saferemovequeryfromurl("b",s));
wl(saferemovequeryfromurl("c",s));
wl(safeaddquerytourl("d","new",s));
wl(safeaddquerytourl("a","newvalue",s));
// 输出如下:
// http://www.cnblogs.com/?b=2&c=3#tag
// http://www.cnblogs.com/?a=1&c=3#tag
// http://www.cnblogs.com/?a=1&b=2#tag
// http://www.cnblogs.com/?a=1&b=2&c=3&d=new#tag
// http://www.cnblogs.com/?a=newvalue&b=2&c=3#tag