Summarize the Request object usage instance of the ASP. NET built-in object

Source: Internet
Author: User
Tags servervariables
The request object is primarily used to obtain data from the client, such as the data that the user fills in the form, the cookie saved on the client, and so on, this article will explain its main role around the request object: Read the form variable, read the query string variable, get the system information on the Web server side. Get the client browser information and so on, interested friends can understand the next

Objective:
The request object is primarily used to obtain data from the client, such as the data that the user fills in the form, the cookie saved on the client, and so on.

I. Overview of the Request object

1. Main attributes

Applicationpath Get the virtual application root path of an ASP. NET application on the server
Browser Gets information about the browser capabilities of the client being requested, the property value is: HttpBrowserCapabilities object
ContentEncoding Gets or sets the character set of the entity body. The property value is the character set encoding object that represents the client
ContentLength Specifies the length, in bytes, of content sent by the client
ContentType Gets or sets the MIME content type of the incoming request.
Cookies Gets the collection of cookies sent by the client, which is the HttpCookieCollection object that represents the cookie variable for the client
Currentexecutionfilepath Gets the virtual path of the current request
FilePath Gets the virtual path of the current request
Files Gets the collection of files uploaded by the client. The property value is a Httpfilecollection object that represents the collection of files uploaded by the client
Form Get a collection of form variables
HttpMethod Gets the HTTP data transfer method used by the client (e.g. get, post, or head)
Item Gets the specified object in the collection of cookies, Form, querystring, or ServerVariables
Params Get a combined set of cookies, Form, querystring, or ServerVariables items
Path Gets the virtual path of the current request
PathInfo Get additional path information for a resource with a URL extension
Physicalapplicationpath Gets the physical file system path of the root directory of the server application that is currently executing
PhysicalPath Gets the physical file path corresponding to the requested URL
QueryString Gets a collection of HTTP query string variables. The property value is: NameValueCollection object, which contains a collection of query string variables sent by the client
RequestType Gets or sets how the client uses HTTP data transfer (GET or POST)
ServerVariables Get a collection of Web server variables
TotalBytes Gets the number of bytes in the current input stream
Url Get information about the current request URL
UserHostAddress Get the IP host address of the remote client

2. Main methods

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

(2) SaveAs (filename,includeheaders): Saves an HTTP request to disk. The parameter filename Specifies the physical drive path, Includeheaders is a Boolean value that specifies whether the HTTP header should be saved to disk.

II. Application of Request object

1. Read the form variable four ways :

(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). Read form variables directly from the properties of the server control

(1). Use the Request.Form property to read form variables

The default value for the method property of the HtmlForm control is post. In this case, when the user submits the page, the form data is sent to the server side as an HTTP header. At this point, you can use the form property of the Request object to read the forms variable. For example: txtUserName and Txtpassword text box controls, you can read their values in the following form: request.form["txtUserName"]; request.form["Txtpassword"]

(2) Use the Request.QueryString property to read form variables

If you set the method property of the HtmlForm control to get, the form data is appended to the server side after the Web address when the user submits the page. In this case, you can use the QueryString property of the Request object to read the form variable. request.querystring["txtUserName"]; request.querystring["Txtpassword"]

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

Regardless of the value of the method property of the HtmlForm control, you can use the Params property of the Request object to read the contents of the form variable, such as request.params["Txtpassword" or request. ["Txtpassword"], the first to get the data submitted by the Get method, it will be in QueryString, Form, servervariable in order to search again.

Request: Contains both of the above methods (the first to get the data submitted by the Get method), it will be in QueryString, Form, servervariable in order to search again. Request.params is a collection of all post and get passed values, and Request.params is actually a collection, which in turn includes Request.QueryString, request. Form, Request.Cookies, and request.servervariable.

Note: When using Request.params, it is best not to have the same name in these collection items. If only one of the data in the Form is needed, but the request is used instead of the Request.Form, then the program will be searched again in querystring and ServerVariable. If QueryString or servervariable has the same name, then the desired value will not be obtained.

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

In addition to the above 3 ways, you can also directly read form variables through the properties of the server control, which is the most common and simplest way to get form data. Example: txtUsername.Text

2. Reading query string variables

When you browse the Web, you often see URLs such as "xxx.aspx?id=8018" in the browser's address bar, where xxx.aspx represents the. aspx Web page that you want to access, followed by a question mark (?) as a query string. The function is to pass the name and value of the variable to the ASP. The query string variables can be generated in several ways.

(1). If you set the method property of the HtmlForm control to get, the form data will be sent to the server side as a query string variable appended to the URL when the user submits the page.
(2). When creating a hypertext link using the <a>...</a> tag or hyperlink control, you can place the query string behind the destination URL and use the question mark "?". To separate the URL from the query string
(3). When calling the Response.Redirect method, if a variable name/value pair is appended to the URL parameter, the value of these variables is appended to the server side when the target page is opened.
(4). When you enter the request URL in the browser address bar, enter the question mark "?" After the URL. and a query string. For example: Http://.../t.aspx? id=8018

In these cases, query string variables can be retrieved through the Request.QueryString property.

The following code:

On the landing page protected void Button1_Click (object sender, EventArgs e) {//Login//if (txtusername.text = "admin" && TXTPW D.text = = "123")//{//session["Info"] = "random value";//Response.Redirect ("Request2_test.aspx? info= "+ txtusername.text); }//else//{//Response.Redirect ("Request2_test.aspx?error= Login failed! "); }/*********************************** method 2****************************************///or if (TxtUserName.Text = = " Admin "&& Txtpwd.text = =" 123 ") {Response.Redirect (" request2_test.aspx? Info= "+ txtUsername.Text +" &check=1 "); } else {Response.Redirect ("request2_test.aspx?error= Login failed! "); } }

On the Verification page

The code is as follows:

protected void Page_Load (object sender, EventArgs e) {//Verify page//if (session["info"]! = NULL && session["info"]. ToString () = = "Any value")//{//Response.Write ("Login Successful! <br> "+ request.querystring[" Info "] +", Welcome to visit this site "); Response.Write ("Landing success!") <br> "+ request[" Info "] +", Welcome to visit this site "); Response.Write ("Login Success!<br>" +request.form["username"]+ ", welcome to visit this site"); }//else//{//Response.Write ("Login Failed");//}/*************************************** method 2*************************** /if (Convert.ToInt32 (request["Check"]) = = 1) {Response.Write ("Login Successful! <br> "+ request.querystring[" Info "] +", Welcome to visit this site "); } else {Response.Write ("Login Failed");}}

3. Obtaining system information on the Web server side

The request object uses the ServerVariables collection object to hold server-side system information that is contained in the HTTP header that is delivered with the HTTP request. The syntax for getting an environment variable 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:

The code is as follows:

Response.Write (request.servervariables["local_addr"]);//The address of the remote server Response.Write ("<br>"); Response.Write (request.servervariables["REMOTE_ADDR"]);//The IP address of the host where the browser resides Response.Write ("<br>"); Response.Write (Request.Browser.Type.ToString ());//Browser Type Response.Write ("<br>"); Response.Write (Request.Browser.Platform.ToString ());//browser is located on the platform Response.Write ("<br>"); Response.Write (request.servervariables["url"]);

4. Get client browser Information

Obtained by the browser property of the Request object. You need to use the browser property to generate an object instance of the HttpBrowserCapabilities type. The HttpBrowserCapabilities class has the following common properties:

The code is as follows:

Response.Write ("Browser type is:" + Request.Browser.Browser.ToString () + "<br>"); Response.Write ("Browser version is:" + Request.Browser.Version.ToString () + "<br>"); Response.Write ("Browser is located on the platform:" + Request.Browser.Platform.ToString () + "<br>"); Response.Write ("Whether the browser supports frames:" + Request.Browser.Frames.ToString () + "<br>"); Response.Write ("browser supports Cookies:" + Request.Browser.Cookies.ToString () + "<br>"); Response.Write ("browser supports JavaScript:" + Request.Browser.JavaScript.ToString () + "<br>");

5. Read Client cookie

A cookie is a way for a server or script to maintain information on a client workstation under the HTTP protocol. A cookie is a small text file that is saved by a Web server in a user's browser and can contain information about a user that is stored in a text file as a name/value pair. Whenever a user connects to a server, the Web site can access cookie information. The cookie is stored in the user's cookie file and can still be invoked the next time the user returns.

A collection of cookies is made up of some cookie objects. The class name of the cookie object is HttpCookie. The main properties of the HttpCookie class are as follows:

When using cookies, you should pay attention to the following points

[1]. When you use a cookie to save request information for a client browser requesting a server page, the length of time you save depends on the expires attribute of the cookie object and can be set as needed. If the cookie expiration date is not set, they are only saved until the browser is closed. Setting the Expires property of a cookie object to DateTime.MaxValue indicates that the cookie will never expire.

[2]. The amount of data stored by a cookie is limited, and most browsers support a maximum capacity of 4096 bytes, so do not use cookies to store large amounts of data.

[3]. Not all browsers support cookies, and the data is stored in clear text on the client computer, so it is best not to use cookies to store sensitive unencrypted data.

[4]. There are two sets of cookies in asp: The Response object's cookie collection and the cookie collection of the request object, but the two have different roles, through which the cookie can be written to the client, through which the cookie stored on the client can be read.

Do the following:

Examples are as follows:

The code is as follows:

protected void Page_Load (object sender, EventArgs e) {HttpCookie c1=request.cookies["UserName"]; HttpCookie C2 = request.cookies["Password"]; if (c1! = NULL | | C2! = NULL) {//When the cookie is saved (that is, "Save or Save Forever"), this can be output, and the second time the Web site is opened with a unified browser, it will output the Response.Write (C1. Value + "Welcome"); }} protected void button1_click (object sender, EventArgs e) {//submit if (TextBox1.Text = = "Admin" && TextBox2.Text = = "123") {Response.Write ("Welcome" +textbox1.text); response.cookies["UserName"]. Value = TextBox1.Text; response.cookies["Password"]. Value = TextBox2.Text; if (DropDownList1.SelectedItem.Text = = "Perpetual Save") {//default cookie expiration time is until close browser//cookie save permanent response.cookies["UserName"]. Expires = DateTime.MaxValue; response.cookies["Password"]. Expires = DateTime.MaxValue; } else {//cookie never save response.cookies["UserName"]. Expires = DateTime.Now; response.cookies["Password"]. Expires = DateTime.Now; } } }

When we open the site again (the same browser), it will pop up "admin welcome"

"Recommended"

1. talk about the use of the two objects: request and response

2. share a Request object small case

3. sharing the Request object in ASP five methods to obtain client data

4. request for an explanation of the ASP system object

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.