Home  >  Article  >  Backend Development  >  Summary of Asp.net built-in object Request object usage examples

Summary of Asp.net built-in object Request object usage examples

零下一度
零下一度Original
2017-05-23 11:45:372857browse

The Request object is mainly used to obtain data from the client, such as data filled in by the user, cookies saved on the client, etc. This article will focus on the Request object and explain its main functions: reading form variables and reading queries. String variable, obtain the system information of the Web server. Obtain client browser information, etc. Interested friends can learn about it

Foreword:
The Request object is mainly used to obtain data from the client, such as the user filling in the form Data, cookies stored on the client, etc.

1. Overview of Request object

1. Main attributes

ApplicationPath Get the virtual application root path of the asp.net application on the server
Browser Get information about the requesting client Information about the browser capabilities of the client, the value of this attribute is: HttpBrowserCapabilities object
ContentEncoding Gets or sets the character set of the entity body. The value of this attribute is the character set Encoding object representing the client
ContentLength Specifies the length of the content sent by the client, in bytes
ContentType Gets or sets the MIME content type of the incoming request.
Cookies Get the Cookie collection sent by the client. The value of this attribute is the HttpCookieCollection object that represents the client's Cookie variable
CurrentExecutionFilePath Get the virtual path of the current request
FilePath Get the virtual path of the current request
Files Get the collection of files uploaded by the client. The value of this attribute is the HttpFileCollection object, which represents the file collection uploaded by the client
Form Get the form variable collection
HttpMethod Get the HTTP data transmission method used by the client (such as get, post or head)
Item Get the specified object in the Cookies, Form, QueryString or ServerVariables collection
Params Get the combined collection of Cookies, Form, QueryString or ServerVariables items
Path Get the virtual path of the current request
PathInfo Get the additional path information of the resource with URL extension
PhysicalApplicationPath Get the physical file system path of the root directory of the currently executing server application
PhysicalPath Get the physical file path corresponding to the requested URL
QueryString Get the HTTP query string variable collection. The value of this property is: NameValueCollection object, which contains a collection of query string variables sent by the client
RequestType Gets or sets the way the client uses HTTP data transmission (get or post)
ServerVariables Get the collection of Web server variables
TotalBytes Get Number of bytes of the current input stream
Url Get information about the current request URL
UserHostAddress Get the IP host address of the remote client

2. Main method

(1)MapPath(VirtualPath): Map the virtual path virtualPath in the currently requested URL to the physical path on the server. The parameter virtualPath specifies the virtual path of the current request, which can be an absolute path or a relative path. The return value of this method is the physical path of the server specified by virtualPath.

(2)SaveAs (Filename, includeHeaders): Save the http request to disk. The parameter filename specifies the physical drive path and includeHeaders is a Boolean value specifying whether HTTP headers should be saved to disk.

2. Application of Request object

1. Four ways to read form variables:

(1) .Use the Request.Form property to read form variables
(2).Use the Request.QueryString property to read form variables
(3).Use the Request.Params property to read form variables
(4 ). Directly read the form variables

through the properties of the server control (1). Use the Request.Form property to read the form variables

Method property of the HtmlForm control The default value is post. In this case, when the user submits the web page, the form data is sent to the server side in the form of HTTP headers. At this point, you can use the Form property of the Request object to read the form variables. For example: txtUserName and txtPassword text box controls, their values ​​can be read in the following form: Request.Form["txtUserName"] ;Request.Form["txtPassword"]

(2) Use Request .QueryString property reads form variables

If the Method property of the HtmlForm control is set to get, when the user submits the web page, the form data will be appended to the URL and sent to the server. In this case, you can use the QueryString property of the Request object to read the form variables. Request.QueryString["txtUserName"] ;Request.QueryString["txtPassword"]

(3) Use the Request.Params property to read form variables

No matter what the Method property of the HtmlForm control is Value, you can use the Params property of the Request object to read the content of the form variable, such as Request.Params["txtPassword"] or Request.["txtPassword"]. The data submitted by GET method is given priority, and it will be in QueryString, Form and ServerVariable are searched in order.

Request: Including the above two methods (the data submitted by GET method is obtained first), it will search in QueryString, Form, and ServerVariable in order. Request.Params is a collection of all values ​​passed by post and get. request.params is actually a collection, which includes request.QueryString, request.Form, request.cookies and request.ServerVariable in order.

Note: When using Request.Params, it is best not to have items with the same name among these collection items. If you only need a piece of data in the Form, but use Request instead of Request.Form, the program will also search in QueryString and ServerVariable. If there happens to be an item with the same name in QueryString or ServerVariable, then the value you get is not the desired value.

(4) Directly read form variables through the properties of the server control

In addition to the above three methods, you can also directly read the form variables through the properties of the server control. This It is the most common and simplest way to obtain form data. For example: txtUserName.Text

2. Read the query string variable

When browsing the web, you often see URLs such as "xxx.aspx?id=8018" displayed in the browser address bar, where xxx.aspx indicates that you want to visit .aspx web page, the content followed by the question mark (?) is the query string, and its function is to transfer the name and value of the variable to this ASP.NET file for processing. Query string variables can be generated in several ways.

(1). If the Method property of the HtmlForm control is set to get, then when the user submits the web page, the form data will be sent to the server as a query string variable attached to the end of the URL.
(2). When using the 3499910bf9dac5ae3c52d5ede7383485…5db79b134e9f6b82c0b36e0489ee08ed tag or the HyperLink control to create a hypertext link, you can place the query string after the target URL and use a question mark "?" to separate the URL and the query. String
(3). When calling the Response.Redirect method, if there are variable name/value pairs attached to the URL parameters, these variable values ​​will be attached to the URL and sent to the server when the target web page is opened.
(4). When entering the request URL in the browser address bar, enter the question mark "?" and the query string after the URL. For example: http://…/t.aspx?Id=8018

In the above situations, the query string variable can be retrieved through the Request.QueryString property.

The following code:

//在登陆页面 protected void Button1_Click(object sender, EventArgs e) { //登陆 //if (txtUserName.Text == "admin" && txtPwd.Text == "123") //{ // Session["Info"] = "随便一个值"; // Response.Redirect("Request2_test.aspx?Info=" + txtUserName.Text); //} //else //{ // Response.Redirect("Request2_test.aspx?error=登陆失败!"); //} /***********************************方法2****************************************/ //或者 if (txtUserName.Text == "admin" && txtPwd.Text == "123") { Response.Redirect("Request2_test.aspx?Info=" + txtUserName.Text + "&check=1"); } else { Response.Redirect("Request2_test.aspx?error=登陆失败!"); } }

On the verification page

The code is as follows:

protected void Page_Load(object sender, EventArgs e) 
{ 
//验证页面 
//if (Session["Info"] != 
null
 && Session["Info"].ToString() == "随便一个值") 
//{ 
// Response.Write("登陆成功!<br>" + Request.QueryString["Info"] + ",欢迎访问本站"); 
// //Response.Write("登陆成功!<br>" + Request["Info"] + ",欢迎访问本站"); 
// //Response.Write("登录成功!<br>"+Request.Form["username"]+",欢迎访问本站"); 
//} 
//else 
//{ 
// Response.Write("登陆失败"); 
//} 
/***************************************方法2**********************************/ 
if (Convert.ToInt32(Request["check"]) == 1) 
{ 
Response.Write("登陆成功!<br>" + Request.QueryString["Info"] + ",欢迎访问本站"); 
} 
else 
{ 
Response.Write("登陆失败"); 
} 
}

3. Obtain system information on the Web server side

The Request object uses the ServerVariables collection object to save the server-side system information. These information variables are included in the HTTP header and transmitted along with the HTTP request. The syntax for obtaining environment variables using the ServerVariables collection object of the Request object is as follows: Request.ServerVariables[environment variable name]

The common information variables saved in the ServerVariables collection object are as follows:

 代码如下:

Response.Write(Request.ServerVariables["LOCAL_ADDR"]);//远端服务器的地址 Response.Write("<br>"); Response.Write(Request.ServerVariables["Remote_ADDR"]);//浏览器所在主机的IP地址 Response.Write("<br>"); Response.Write(Request.Browser.Type.ToString());//浏览器的类型 Response.Write("<br>"); Response.Write(Request.Browser.Platform.ToString());//浏览器所在的平台 Response.Write("<br>"); Response.Write(Request.ServerVariables["url"]);

4.取得客户端浏览器信息

通过Request对象的Browser属性得到。需要利用Browser属性生成一个HttpBrowserCapabilities类型的对象实例。HttpBrowserCapabilities类具有的常用属性如下:

 代码如下:

Response.Write("浏览器的类型是:" + Request.Browser.Browser.ToString()+"<br>"); Response.Write("浏览器的版本是:" + Request.Browser.Version.ToString()+"<br>"); Response.Write("浏览器的所在平台是:" + Request.Browser.Platform.ToString()+"<br>"); Response.Write("浏览器是否支持框架:" + Request.Browser.Frames.ToString()+"<br>"); Response.Write("浏览器是否支持Cookies:" + Request.Browser.Cookies.ToString()+"<br>"); Response.Write("浏览器是否支持Javascript:" + Request.Browser.JavaScript.ToString()+"<br>");

5.读取客户端Cookie

Cookie是在HTTP协议下服务器或脚本可以维护客户工作站上信息的一种方式。Cookie是由Web服务器保存在用户浏览器上的小文本文件,它可以包含有关用户的信息,这些信息以名/值对的形式储存在文本文件中。无论何时,只要用户连接接到服务器,Web站点就可以访问Cookie信息。Cookie保存在用户的Cookie文件中,当下一次用户返回时,仍然可以对它进行调用。

Cookies集合是由一些Cookie对象组成的。Cookie对象的类名为HttpCookie。HttpCookie类的主要属性如下:

使用Cookie时,应注意以下几点

[1].使用Cookie保存客户端浏览器请求服务器页面的请求信息时,保存时间的长短取决于Cookie对象的Expires属性,可以根据需要来设置。若未设置Cookie的失效日期,则它们仅保存到关闭浏览器为止。若将Cookie对象的Expires属性设置为DateTime.MaxValue,则表示Cookie永远不会过期。

[2].Cookie存储的数据量有所限制,大多数浏览器支持的最大容量为4096字节,因此不要用Cookie来保存大量数据。

[3].  并非所有浏览器都支持Cookie,并且数据是以明文形式保存在客户端计算机中,因此最好不要用Cookie来保存敏感的未加密数据。

[4].在ASP.NET中有两个Cookies集合,即:Response对象的Cookies集合和Request对象的Cookies集合,但两者的作用有所不同,通过前者可以将Cookie写入客户端,通过后者可以读取存储在客户端的Cookie。

如下操作:

示例如下:

代码如下:

protected void Page_Load(object sender, EventArgs e) 
{ 
HttpCookie c1=Request.Cookies["UserName"]; 
HttpCookie c2 = Request.Cookies["Password"]; 
if (c1 != null || c2 != null) 
{ 
//当保存完Cookie之后(也就是说"保存或永久保存"),这个才能输出,当第二次用统一浏览器打开该网站的时候就会输出 
Response.Write(c1.Value + "欢迎光临"); 
} 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
//提交 
if (TextBox1.Text == "admin" && TextBox2.Text == "123") 
{ 
Response.Write("欢迎光临"+TextBox1.Text); 
Response.Cookies["UserName"].Value = TextBox1.Text; 
Response.Cookies["Password"].Value = TextBox2.Text; 
if (Dro
pDo
wn
List
1.SelectedItem.Text == "永久保存") 
{ 
//默认cookies失效时间是直到关闭浏览器 
//Cookie保存永久 
Response.Cookies["UserName"].Expires = DateTime.MaxValue; 
Response.Cookies["Password"].Expires = DateTime.MaxValue; 
} 
else 
{ 
//Cookie永不保存 
Response.Cookies["UserName"].Expires = DateTime.Now; 
Response.Cookies["Password"].Expires = DateTime.Now; 
} 
} 
}

当我们再次打开该网站(同一浏览器)的时候,就会弹出“admin欢迎光临"

【相关推荐】

1. 谈谈Request和Response这两个对象的使用

2. 分享一个Request对象小案例

3. 分享asp中request对象五个获取客户端资料的方法

4. 详解ASP.NET 系统对象之Request

The above is the detailed content of Summary of Asp.net built-in object Request object usage examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn