HttpRequest類


一、HttpRequest的作用

  HttpRequest的作用是令到Asp.net能夠讀取客戶端發送HTTP值。比如表單、URL、Cookie傳遞過來的參數。

  返回字符串的那些值就不說了,那些基本上都是與HTTP請求報文相關的東西。

   現在看看返回NameValueCollection對象的東東,這個對象只是為了存儲返回的東西。

  1、Request.Headers;

  這個東西返回的是什么呢?寫個實例:

        public ActionResult Index()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            NameValueCollection headersCollect = request.Headers;
            string[] headArr = headersCollect.AllKeys;
            foreach (string str in headArr)
            {
                Response.Write(str + ":" + headersCollect.Get(str) + ";<br/>");
            }
            return View();
        }

  看看在瀏覽器輸出:

  再用火狐看看HTTP請求報文的請求頭信息:

   明顯可以看到,這個request.Headers返回的就是請求頭信息的一個NameValueCollection集合。

   2、Request.Form

  這個屬性獲取的是瀏覽器提交的表單內容,也是返回NameValueCollection對象,這個對象中包含了所有的表單鍵值對內容。

  看前台HTML代碼:

<form action="/Home/GetForm" method="post">
    <p>姓名:<input type="text" name="Name" /></p>  //輸入張三
    <p>年齡:<input type="text" name="Age" /></p>   //輸入12
    <p>性別:<input type="radio" name="male" value="man" />&nbsp; <input type="radio" name="male" value="woman" /></p>  //選擇 男
    <p><input type="submit" value="提交" /></p>
</form>

  后台代碼:

        public ActionResult GetForm()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            NameValueCollection FormCollect =  request.Form;
            foreach (string str in FormCollect)
            {
                Response.Write(str + ": " + FormCollect.Get(str) + "<br/>");
            }
            return Content("鍵值對數目:" + FormCollect.Count);
        }

  瀏覽器輸出:

Name: 張三
Age: 12
male: man
鍵值對數目:3

   3、Request.QueryString

  該屬性的作用是將URL中的參數全部保存到NameValueCollection集合中。

        public ActionResult TestCookie()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc = System.Web.HttpContext.Current.Request.QueryString;
            Response.Write(nvc.Count + "   ");  //輸出路徑中參數集合的總數
            if (nvc.Count > 0)
            {
                foreach (string str in nvc.AllKeys)
                {
                    Response.Write(str + ": " + nvc.Get(str) + ";  ");      //遍歷url參數集合,輸出參數名與值
                }
            }
            return View();
            //當路徑為http://localhost:22133/Home/testCookie?id=1&name=張三&Age=23
            //輸出3 id: 1; name: 張三; Age: 28;             

  4、Params,Item與QueryString、Forms的區別

  • Get請求用QueryString;
  • Post請求用Forms;
  • Parms與Item可以不區分Get請求還是Post請求;

  Params與Item兩個屬性唯一不同的是:Item是依次訪問這4個集合,找到就返回結果,而Params是在訪問時,先將4個集合的數據合並到一個新集合(集合不存在時創建), 然后再查找指定的結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM