2008-12-17 69 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)