ASP.NET中Get和Post的用法
單form的提交有兩種方式,一種是get的方法,一種是post 的方法.看下面代碼,理解ASP.NET Get和Post兩種提交的區(qū)別:
- < form id="form1" method="get" runat="server">
- < div>
- 你的名字< asp:TextBox ID="name" runat="server">< /asp:TextBox>< br />
- < br />
- 你的網(wǎng)站< asp:TextBox ID="website" runat="server">< /asp:TextBox>< br />
- < br />
- < br />
- < asp:Button ID="Button1" runat="server" Text="send" />< br />
- < br />
- < br />
- 學習request 和 response的用法< br />
- < br />
- < br />
- < /div>
- < /form>
- < form id="form2" method="post" runat="server">
- < div>
- 你的名字< asp:TextBox ID="name2" runat="server">< /asp:TextBox>< br />
- < br />
- 你的網(wǎng)站< asp:TextBox ID="website2" runat="server">< /asp:TextBox>< br />
- < br />
- < br />
- < asp:Button ID="Button2" runat="server" Text="send" />< br />
- < br />
- < br />
- 學習request 和 response的用法< br />
- < br />
- < br />
- < /div>
- < /form>
從URL中可看出ASP.NET Get和Post的區(qū)別.那么那如何編程實現(xiàn)數(shù)據(jù)的接收呢?
第1種,接收用get 方法傳輸?shù)臄?shù)據(jù)的寫法:
- protected void Page_Load(object sender, EventArgs e)
- {
- string id = Request.QueryString["name"];
- string website = Request.QueryString["website"];
- Response.Write(id + "< br>" + website);
- Response.Write("你使用的是" + Request.RequestType + "方式傳送數(shù)據(jù)");
- }
第2種,接收用post 方法傳輸?shù)臄?shù)據(jù)的寫法:
- protected void Page_Load(object sender, EventArgs e)
- {
- string id2 = Request.Form["name2"];
- string website2 = Request.Form["website2"];
- Response.Write(id2 + "< br>" + website2);
- Response.Write("你使用的是" + Request.RequestType + "方式傳送數(shù)據(jù)");
- }
- string id4 = Request["name4"];
- string website4 = Request["website4"];
- Response.Write(id4 + "< br>" + website4);
第3種,同時接受get和post 方法傳送數(shù)據(jù)的代碼寫法:
A 寫法
- string id3 = Request.Params["name3"];
- string website3 = Request.Params["website3"];
- Response.Write(id3 + "< br>" + website3);
B 寫法
- string id4 = Request["name4"];
- string website4 = Request["website4"];
- Response.Write(id4 + "< br>" + website4);
表單提交中,ASP.NET的Get和Post方式的區(qū)別歸納如下幾點:
1. get是從服務(wù)器上獲取數(shù)據(jù),post是向服務(wù)器傳送數(shù)據(jù)。
2. get是把參數(shù)數(shù)據(jù)隊列加到提交表單的ACTION屬性所指的URL中,值和表單內(nèi)各個字段一一對應(yīng),在URL中可以看到。post是通過HTTP post機制,將表單內(nèi)各個字段與其內(nèi)容放置在HTML HEADER內(nèi)一起傳送到ACTION屬性所指的URL地址。用戶看不到這個過程。
3. 對于get方式,服務(wù)器端用Request.QueryString獲取變量的值,對于post方式,服務(wù)器端用Request.Form獲取提交的數(shù)據(jù)。
4. get傳送的數(shù)據(jù)量較小,不能大于2KB。post傳送的數(shù)據(jù)量較大,一般被默認為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。
5. get安全性非常低,post安全性較高。但是執(zhí)行效率卻比Post方法好。
建議:
1、get方式的安全性較Post方式要差些,包含機密信息的話,建議用Post數(shù)據(jù)提交方式;
2、在做數(shù)據(jù)查詢時,建議用Get方式;而在做數(shù)據(jù)添加、修改或刪除時,建議用Post方式。
【編輯推薦】