我一直希望找到一個框架內置的解決方案,但沒有。 (那些在框架方法需要對大量的工作,使之簡單,乾淨)
嘗試幾種選擇我目前使用下面的擴展方法後:(發佈一個更好的解決方案,或者如果你有一個評論)
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