我一直希望找到一个框架内置的解决方案,但没有。 (那些在框架方法需要对大量的工作,使之简单,干净)
尝试几种选择我目前使用下面的扩展方法后:(发布一个更好的解决方案,或者如果你有一个评论)
public static class UriExtensions
{
public static Uri AddQuery(this Uri uri, string name, string value)
{
string newUrl = uri.OriginalString;
if (newUrl.EndsWith("&") || newUrl.EndsWith("?"))
newUrl = string.Format("{0}{1}={2}", newUrl, name, value);
else if (newUrl.Contains("?"))
newUrl = string.Format("{0}&{1}={2}", newUrl, name, value);
else
newUrl = string.Format("{0}?{1}={2}", newUrl, name, value);
return new Uri(newUrl);
}
}
这种扩展方法使非常干净重定向和URI操作:
Response.Redirect(Request.Url.AddQuery("ProductID", productId).ToString());
// Will generate a URL of www.google.com/search?q=asp.net
var url = new Uri("www.google.com/search").AddQuery("q", "asp.net")
,将以下网址的工作:
"http://www.google.com/somepage"
"http://www.google.com/somepage?"
"http://www.google.com/somepage?OldQuery=Data"
"http://www.google.com/somepage?OldQuery=Data&"
的ParseQueryString只需要一个URL(不是路径)的查询字符串的一部分,它不会与一个问号前缀它。 – Yona 2008-12-17 17:28:37
而且?将查询字符串从URL中取出是很简单的(例如,使用System.Uri类或简单的字符串.Split或字符串。子字符串),一旦你有它,你知道它不能在内部包含问号(他们会被编码),所以只需要url +“?” + queryString.ToString()。 – technophile 2008-12-18 02:50:35