C#获取URL参数值(NameValueCollection)

在写程序的时候,我们经常需要对页面进行传参数,比如page?id=1234,那么在page这个页面中就直接可以使用string id = Request.QueryString["id"]; 来获取参数id的值1234了。这是一个人人都知道的基础知识。

上面的方法:Request.QueryString,它会把传入的URL进行分析,并把结果保存在一个键值(key value)的Collection中,我们只要通过设置key值,就可以返回这个key所对应的value了。

假设这个URL不是通过请求进来的,我们是没有办法通过Request来获取URL的参数值的,我们是否可以通过一个字符串string url = "http://www.google.com/page?id=1234"中分析出Collection[key]=value呢?而且很多时候我们的URL的参数都是经过UrlEncode编码的,这个编码通常来说会是Encoding.UTF8或者Encoding.GetEncoding("gb2312"),需要提醒你的是:Baidu的URL是使用gb2312的,而Google是使用UTF8的。那对于传入的字符串我们如何确认是该使用gb2312还是UTF8来解码呢?

在Baidu或者Google搜索到相关的解决办法中,你会看到这样的说法,那就是通过正则表达式去匹配URL,例如:Regex urlRegex = new Regex(@"(?:^|\?|&)courseid=(\d*)(?:&|$)"); 但是我比较怀疑通过这个方法分析出来的数据完整性,它有办法确保匹配出所有数据吗?后来我想到了模拟Microsoft .NET Framework中Request的方法来解决这个问题。其实上面的string id = Request.QueryString["id"]; 也可以写成 System.Collections.Specialized.NameValueCollection col = Request.QueryString; string strID = col[”id”];所以让我们来构造这个NameValueCollection吧!

 

  private string ResultDataSign(string postData)    

     {      

       //string echostr = Var.SYS_OAUTH_VERIFY_CODE;  

           NameValueCollection nameValue = GetQueryString(postData);     

       StringBuilder builder = new StringBuilder();       

      if (nameValue != null)     

        {         

        int count = 0;       

          String[] sortedKeys = nameValue.AllKeys;   

              Array.Sort(sortedKeys);       

          foreach (String key in sortedKeys)        

         {            

         count++;            

         builder.Append(key + "=" + nameValue[key]);      

               if (count != nameValue.Count)         

            {            

             builder.Append("&");       

              }            

     }     

        }         

    return md5(builder.ToString()).ToLower();      

   }

        private string md5(String input)      

   {      

       MD5CryptoServiceProvider Md5 = new MD5CryptoServiceProvider();     

        return BitConverter.ToString(Md5.ComputeHash(Encoding.UTF8.GetBytes(input))).Replace("-", "");  

       }     

    public static NameValueCollection GetQueryString(string queryString)   

      {     

        return GetQueryString(queryString, null, true);   

      }

        /// <summary>   

      /// 将查询字符串解析转换为名值集合.       

  /// </summary>  

       /// <param name="queryString"></param>    

     /// <param name="encoding"></param>     

    /// <param name="isEncoded"></param>   

      /// <returns></returns>  

       public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)    

     {          

   queryString = queryString.Replace("?", "");    

         NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);       

      if (!string.IsNullOrEmpty(queryString))     

        {             

    int count = queryString.Length;       

          for (int i = 0; i < count; i++)       

          {        

             int startIndex = i;      

               int index = -1;           

          while (i < count)               

      {              

           char item = queryString[i];   

                      if (item == '=')      

                   {             

                if (index < 0)       

                      {       

                          index = i;        

                     }          

               }      

                   else if (item == '&')          

               {             

                break;          

               }        

                 i++;    

                 }       

              string key = null;        

             string value = null;   

                  if (index >= 0)    

                 {     

                    key = queryString.Substring(startIndex, index - startIndex);     

                    value = queryString.Substring(index + 1, (i - index) - 1);     

                }         

            else       

              {            

             key = queryString.Substring(startIndex, i - startIndex);     

                }       

              if (isEncoded)              

       {                   

      result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);     

                }     

                else      

               {         

                result[key] = value;     

                }          

           if ((i == (count - 1)) && (queryString[i] == '&'))  

                   {         

                result[key] = string.Empty;         

            }          

       }      

       }        

     return result;   

      }    

     /// <summary>   

      /// 解码URL.  

       /// </summary>  

       /// <param name="encoding">null为自动选择编码</param>

        /// <param name="str"></param>   

      /// <returns></returns>     

    public static string MyUrlDeCode(string str, Encoding encoding)      

   {      

       if (encoding == null)    

         {          

       Encoding utf8 = Encoding.UTF8;                 //首先用utf-8进行解码             

                        string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);                 //将已经解码的字符再次进行编码.     

            string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();       

          if (str == encode)       

              encoding = Encoding.UTF8;     

            else               

      encoding = Encoding.GetEncoding("gb2312");   

          }        

     return HttpUtility.UrlDecode(str, encoding);    

     }

用到System.web的命名空间

posted on 2015-05-03 18:22  zrSoldier  阅读(3039)  评论(0编辑  收藏  举报