1. 程式人生 > >C# 獲取aspx頁面中所有隱藏控制元件的兩種方法

C# 獲取aspx頁面中所有隱藏控制元件的兩種方法

適合.NET4.0 以上版本

  /// <summary>
    /// 獲取ASPX頁面中隱藏post值	Viewstae 等
    /// </summary>
    /// <param name="Url"></param>
    /// <returns></returns>
    public Dictionary<string, string> GetViewHiddenData(string Url)
    {
      HttpClient httpClient = new HttpClient();
      httpClient.MaxResponseContentBufferSize = 256000;
      httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
      HttpResponseMessage response = httpClient.GetAsync(new Uri(Url)).Result;
      var result = Regex.Matches(response.Content.ReadAsStringAsync().Result, @"<input type=""hidden""[^>]*?.*?\/>")
                              .Cast<Match>().Select(mx => mx.Groups[0].Value.TrimStart().TrimEnd()).ToList();
      Dictionary<string, string> returnHidden = new Dictionary<string, string>();
      foreach (var item in result)
      {
        //獲取 隱藏域中的 id  value
        //var reg = @"(?isn)<input((?!([<>]|id=)).)+id=""(?<id>[^""<>]+)""[^<>]*?value=""(?<value>[^<>""]*)""";
        //	var keyvalue = Regex.Match(item, reg);
        //returnHidden.Add(keyvalue.Groups[1].Value, keyvalue.Groups[2].Value);
        var key = Regex.Match(item, @"<input type=""hidden""[^>]*?[^>]+?id=""([\s\S]+?)""[^>]+>").Groups[1].Value;
        var value = Regex.Match(item, @"<input type=""hidden""[^>]*?[^>]+?value=""([\s\S]+?)""[^>]+>").Groups[1].Value;
        returnHidden.Add(key, value);
      }
      //用完要記得釋放
      httpClient.Dispose();
      return returnHidden;
    }

GetViewHiddenData 使用方法:

 var paramList = new List<KeyValuePair<String, String>>();
        GetViewHiddenData("http://www.sd.xd.com/sdweb/HomePage/CntrYardQuery/QueryByBlno.aspx").ToList().
ForEach(x => paramList.Add(new KeyValuePair<string, string>(x.Key, x.Value)));

適用於.NET4.0一下版本        由於.NET4.0版本一下不包含System.Net.Http.dll

/// <summary>
    /// 共用獲取隱藏,適應於NET4.0一下 由於不支援.net.http而編寫的方法
    /// </summary>
    /// <param name="Url"></param>
    /// <param name="locationHref"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public Dictionary<string, string> GetViewHiddenDataToNet40End(string Url, string encoding)
    {
      Dictionary<string, string> returnHidden = new Dictionary<string, string>();
      HttpWebRequest getRequset = (HttpWebRequest)HttpWebRequest.Create(Url);//建立http 請求
      getRequset.Method = "Get";
      getRequset.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
      getRequset.Headers.Add("Accept-Language", "zh-Hans-CN,zh-Hans;q=0.5");
      getRequset.Headers.Add("Accept-Encoding", "gzip, deflate");
      getRequset.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko";
      getRequset.KeepAlive = true;
      getRequset.AutomaticDecompression = DecompressionMethods.GZip;
      // getRequset.Host = "bizweb.qdcdc.com";
      getRequset.Headers.Add("Access-Control-Allow-Origin", "*");

      HttpWebResponse response = (HttpWebResponse)getRequset.GetResponse();
      var retString = string.Empty;
      using (Stream responsestream = response.GetResponseStream())
      {
        using (StreamReader sr = new StreamReader(responsestream, System.Text.Encoding.GetEncoding(encoding)))
        {
          retString = sr.ReadToEnd();
        }
      }
      var result = Regex.Matches(retString, @"<input type=""hidden""[^>]*?.*?\/>")
                              .Cast<Match>().Select(mx => mx.Groups[0].Value.TrimStart().TrimEnd()).ToList();
      foreach (var item in result)
      {
        //獲取 隱藏域中的 id  value
        var key = Regex.Match(item, @"<input type=""hidden""[^>]*?[^>]+?id=""([\s\S]+?)""[^>]+>").Groups[1].Value;
        var value = Regex.Match(item, @"<input type=""hidden""[^>]*?[^>]+?value=""([\s\S]+?)""[^>]+>").Groups[1].Value;
        returnHidden.Add(key, value);
      }
      return returnHidden;
    }

GetViewHiddenDataToNet40End 使用方法:

 var postLoginUrl = "http://www.xx.com.cn/zcxt/login.aspx";
      List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
      //處理.net http在.net4.0以下版本沒有,xp 2003不執行
      // GetViewHiddenData(postLoginUrl).ToList().ForEach(x => paramList.Add(new KeyValuePair<string, string>(x.Key, x.Value)));
      GetViewHiddenDataToNet40End(postLoginUrl, "utf-8").ToList().ForEach(x => paramList.Add(new KeyValuePair<string, string>(x.Key, x.Value)));