2008-12-17 73 views
3

我在當前的應用程序中遇到了一個問題,需要在基類Page類(我的所有頁面從中繼承)中查詢字符串以解決問題。由於我的一些頁面使用查詢字符串,我想知道是否有任何類提供乾淨和簡單的查詢字符串操作。的代碼乾淨的方式爲Web請求生成QueryString參數

實施例:

// What happens if I want to future manipulate the query string elsewhere 
// (e.g. maybe rewrite when the request comes back in) 
// Or maybe the URL already has a query string (and the ? is invalid) 

Response.Redirect(Request.Path + "?ProductID=" + productId); 

回答

4

HttpUtility.ParseQueryString使用,因爲有人建議(然後刪除)。

這將工作,因爲該方法的返回值實際上是HttpValueCollection,它繼承NameValueCollection(並且是內部的,您不能直接引用它)。然後,您可以正常設置集合中的名稱/值(包括添加/刪除),並調用ToString - 這將生成完成的查詢字符串,因爲HttpValueCollection會覆蓋ToString以重現實際的查詢字符串。

+0

的ParseQueryString只需要一個URL(不是路徑)的查詢字符串的一部分,它不會與一個問號前綴它。 – Yona 2008-12-17 17:28:37

+1

而且?將查詢字符串從URL中取出是很簡單的(例如,使用System.Uri類或簡單的字符串.Split或字符串。子字符串),一旦你有它,你知道它不能在內部包含問號(他們會被編碼),所以只需要url +「?」 + queryString.ToString()。 – technophile 2008-12-18 02:50:35

4

我一直希望找到一個框架內置的解決方案,但沒有。 (那些在框架方法需要對大量的工作,使之簡單,乾淨)

嘗試幾種選擇我目前使用下面的擴展方法後:(發佈一個更好的解決方案,或者如果你有一個評論)

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&" 
+0

如果名稱或值中包含非法字符(例如?或&),會發生什麼情況?並使用System.Uri,但做你自己的解析,而不是使用查詢屬性是沒有意義的。 – technophile 2008-12-18 02:53:24

2

注意,無論你使用的路線,你真的應該編碼值 - Uri.EscapeDataString應該爲你做的:

string s = string.Format("http://somesite?foo={0}&bar={1}", 
      Uri.EscapeDataString("&hehe"), 
      Uri.EscapeDataString("#mwaha")); 
0

我最常做的就是重建的查詢字符串。請求有一個QueryString集合。

您可以通過迭代器獲取當前(未編碼)的參數,並將它們與適當的分隔符一起加入(隨編碼)。

優點是Asp.Net爲您完成了原始解析,因此您不必擔心邊緣情況,如尾隨&和?s。

0

檢查此!!!

// First Get The Method Used by Request i.e Get/POST from current Context 
string method = context.Request.HttpMethod; 

// Declare a NameValueCollection Pair to store QueryString parameters from Web Request 
NameValueCollection queryStringNameValCollection = new NameValueCollection(); 

if (method.ToLower().Equals("post")) // Web Request Method is Post 
{ 
    string contenttype = context.Request.ContentType; 

    if (contenttype.ToLower().Equals("application/x-www-form-urlencoded")) 
    { 
     int data = context.Request.ContentLength; 
     byte[] bytData = context.Request.BinaryRead(context.Request.ContentLength); 
     queryStringNameValCollection = context.Request.Params; 
    } 
} 
else // Web Request Method is Get 
{ 
    queryStringNameValCollection = context.Request.QueryString; 
} 

// Now Finally if you want all the KEYS from QueryString in ArrayList 
ArrayList arrListKeys = new ArrayList(); 

for (int index = 0; index < queryStringNameValCollection.Count; index++) 
{ 
    string key = queryStringNameValCollection.GetKey(index); 
    if (!string.IsNullOrEmpty(key)) 
    { 
     arrListKeys.Add(key.ToLower()); 
    } 
} 
0

我找到了自己的方式來輕鬆操作get參數。

public static string UrlFormatParams(this string url, string paramsPattern, params object[] paramsValues) 
{ 
    string[] s = url.Split(new string[] {"?"}, StringSplitOptions.RemoveEmptyEntries); 
    string newQueryString = String.Format(paramsPattern, paramsValues); 
    List<string> pairs = new List<string>(); 

    NameValueCollection urlQueryCol = null; 
    NameValueCollection newQueryCol = HttpUtility.ParseQueryString(newQueryString); 

    if (1 == s.Length) 
    { 
     urlQueryCol = new NameValueCollection(); 
    } 
    else 
    { 
     urlQueryCol = HttpUtility.ParseQueryString(s[1]); 
    } 



    for (int i = 0; i < newQueryCol.Count; i++) 
    { 
     string key = newQueryCol.AllKeys[i]; 
     urlQueryCol[key] = newQueryCol[key]; 
    } 

    for (int i = 0; i < urlQueryCol.Count; i++) 
    { 
     string key = urlQueryCol.AllKeys[i]; 
     string pair = String.Format("{0}={1}", key, urlQueryCol[key]); 
     pairs.Add(pair); 
    } 

    newQueryString = String.Join("&", pairs.ToArray()); 

    return String.Format("{0}?{1}", s[0], newQueryString); 
} 

使用它像

"~/SearchInHistory.aspx".UrlFormatParams("t={0}&s={1}", searchType, searchString)