Asp. NET built-in object detailed

Source: Internet
Author: User
Tags html header http post numeric value sessions terminates server memory

(1) brief description of ASP. NET built-in objects.

Answer: ASP. NET provides built-in objects for page, Request, Response, Application, session, Server, mail, and cookies. These objects make it easier for users to collect information sent through a browser request, respond to browsers, and store user information for other specific state management and page information delivery.

(2) briefly response object.

A: The response object is used to access the created and client-side response, outputting information to the client, which provides HTTP variables that identify the server and performance, the information sent to the browser, and the information stored in the cookie. It also provides a series of methods for creating output pages, such as ubiquitous response. Write method.

(3) Briefly describe the request object.

A: The request object is used to obtain all the information that the client provides when requesting a page or sending a Form, including HTTP variables that can identify browsers and users, cookie information stored on the client, and values appended to the URL (query string or page < Form The value within the HTML control in the > Segment).

(4) briefly Application object.

A: In the environment, the Application object comes from the Httpapplictionstat class. It can share common information between multiple requests, connections, or it can act as a conduit for information delivery between individual request connections. Use the Application object to hold the variable we want to pass. Because the Application object is valid throughout the application lifecycle, it can be accessed on different pages, as easily as using global variables.

(5) Briefly describe the session object.

A: The session object is a number that the server gives the client. When a Web server is running, there may be several users browsing the Web site that is browsing the server. When each user first connects to the WWW server, he establishes a session with the server, and the server automatically assigns a SessionID to identify the user's unique identity. Specifically, the session object's variables are only valid for a user, and different user sessions are stored with variables of the different conversation objects. In the network environment, the variables of the session object are life cycle, and if the variables of the session object are not refreshed at the specified time, the system terminates the variables.

(6) A brief description of the server object.

A: The server object provides access to methods and properties on the server. Most of these methods and properties are serviced as functionality of the utility. The server object is also a member of the Page object, primarily providing the functionality required to process page requests, such as building COM objects, compiling code for strings, and so on.

(7) A brief description of the cookie object.

A: A cookie is a small piece of text that is stored by the browser on the client system (the hard disk) and is a marker. Embedded in the user's browser by the Web server to identify the user and send each user request to the Web server. The value of cookies is much more complex than the value of a S other collections (such as form and server Variables).

(8) A brief description of the mail object.

A: was given a new object to send email, called smtpmail, and the mail object was actually implemented by the System.Web.Mail class library (class library). This class library consists of MailMessage objects, SmtpMail objects, MailFormat objects, and MailAttachment objects, which cooperate with each other to complete the sending of e-mail.

(9) A brief description of Get transmission mode.


ASP. NET common built-in objects (i)

Asp. NET, the built-in objects and function descriptions are as follows:
Description of Object name function
Page is used to manipulate the entire page
Response is used to output information to the browser
Request is used to get information from the browser
Server provides some of the properties and methods
Application is used to share global information between multiple sessions and requests
Sessions are used to store session information for a specific user
Cookies are used to set or get cookie information
A.. Page Object
The Page object is implemented by the page class in the System.Web.UI namespace, and the page class is associated with a file with an. aspx extension that is compiled as a Page object at run time and cached in server memory. The common properties, methods, and events provided by the Page object are as follows:
Name Feature description
The IsPostBack property gets a value that indicates whether the page is being loaded in response to a client postback
The IsValid property gets a value that indicates whether the page passes validation
The Application property gets the Application object for the current WEB request.
Request property gets the HttpRequest object of the requested page
The response property gets the HttpResponse object associated with the Page. This object enables you to send HTTP response data to the client and contains information about the response.
The session property gets the current session object provided by
The server property gets the server object, which is an instance of the HttpServerUtility class.
The DataBind method binds the data source to the invoked server control and all its child controls
The RegisterClientScriptBlock method emits a client script block to the page
Init event occurs when a server control initializes
The Load event occurs when the server control is loaded into the Page object
Unload event occurs when a server control is unloaded from memory

1.IsPostBack Properties
The IsPostBack property is used to obtain a Boolean value that, if true, indicates that the current page is loaded in response to a client postback (for example, by clicking a button), otherwise the current page is loaded and accessed for the first time.
private void Page_Load (object sender, System.EventArgs e)
if (! Page.IsPostBack)
Label1.Text = "The page is loaded for the first time. ";
Label1.Text = "The page is loaded for the second or second time. ";
IsValid Property
The IsValid property is used to obtain a Boolean value that indicates whether the page validation was successful, or true if the page validation was successful or false. Typically used in a page that contains a validation server control, the value of the IsValid property is true only if all validation server controls are validated successfully.
private void Button_Click (Object Sender, EventArgs e)
if (Page.IsValid = = true)//can also be written as if (Page.IsValid)
MyLabel. text= "You enter the information through verification!";
MyLabel. text= "Your input is incorrect, please check and re-enter." ";
Two Request Object
The request object is implemented by the class System.Web.HttpRequest. When a customer requests a page, all request information, including the request header, request method, client base information, and so on, are encapsulated in the request object, which can be read by the requests object. The properties and methods commonly used by the request object are shown below.
Name Feature description
Cookies property gets the collection of cookies sent by the client
Form property gets the collection of form variables
QueryString property gets the HTTP query string variable collection
Form form data is submitted to the server in two ways: Get and post.
I... Get is to add the parameter data queue to the URL that refers to the action attribute of the submission form, and the value corresponds to each field one by one in the form, as you can see in the URL. Post is the HTTP post mechanism that places the fields in the form and their contents in the HTML header to the URL address that the action attribute refers to. This process is not visible to the user.
Ii.. For Get mode, the server end uses Request.QueryString to obtain the value of the variable, and for the Post method, the server end uses Request.Form to obtain the submitted data.
The amount of data transferred by III is less than 2KB. Post transfers have a large amount of data, which is generally default to unrestricted. In theory, however, the maximum number of IIS4 is 100KB in 80KB,IIS5.
IV. Get security is very low, post security is high.
Form data collection
Use the form collection of request to get the form data that the client sends through the POST method, for example, There are two pages on the server form.htm and do.aspx,form.htm contain a form, the form transmits data by post, and the form is submitted to the do.aspx in the same directory. The code for Form.htm is as follows:
<title> use post to transmit data </title>
<form method= "POST" action= "do.aspx" >
Please enter your name: <input type= "text" name= "Mingzi" ><br>
<input type= "Submit" value= "submitted" >
request.form["Mingzi" will be used in do.aspx to get the user input name, and the do.aspx code is as follows:
private void Page_Load (Object O,eventargs E)
The form data is displayed when the page loads
String Strmessage= "Your name is:"; Define a string variable and assign an initial value
strmessage+= request.form["Mingzi"]; String form data to a variable
Response.Write (strmessage);//Output variable

QueryString Data collection
You can use the QueryString collection to obtain form data that is passed by the client through get methods, and if you change the method property value of a form in form.htm from post to get, then in do.aspx you need to pass Request.QueryString [" Mingzi "] to get the name of the input. Because the Get method transmits data with certain limitations and is not secure, the form generally does not use got methods.
private void Page_Load (object sender, System.EventArgs e)
if (request.querystring["Mingzi"]. ToString ()!= "")
Response.Write ("Your name is:" +request.querystring["Mingzi"). ToString ());
In Web application development, querystring is often used to get the value of a variable in a URL query string, as is the case with the use of a Get method for routing form data. For example, the client uses the following address request: Http://localhost/doit.aspx?name=zhangsan&sex=nan
or open the following hyperlink:
<a href= "Http://localhost/doit.aspx?name=zhangsan&sex=nan" >doit.aspx</a>
You can use request.querystring["name" and request.querystring["sex" in doit.aspx to get the corresponding values Zhangsan and Nan.


I would like to write a summary of the built-in object of the article, the results found that a good online, turned over

Asp. NET's built-in object introduction

The request object is primarily for the server to obtain some data from the client browser, including parameters, cookies, and user authentication that are passed by post or get methods from the HTML table. Because the request object is one of the members of the Page object, you can use it directly without making any declarations in the program;
Its class name is HttpRequest
Many properties, but few methods, only one binaryread ()
1. Use the Request.Form property to get the data
This property is used to read the form data between <Form></Form>. Note: The Submit method is set to "Post".
Compared to the Get method, a post method is used to send large amounts of data to the server side
2. Obtaining data using the Request.QueryString property
The Querysting property of the request object can get a collection of HTTP query string variables. With this property, we can read the address information http://localhost/aaa.aspx?uid=tom&pwd=abc the data that is identified in the Red section.
Note: The Submit method is set to "get"
3. Question: Request.Form is used when the form is submitted as post, and Request.QueryString is used for the form submission to get, and if the error is used, the data is not obtained.
WORKAROUND: Use Request ("element name") to simplify the operation.
4.request.servervariables ("Environment variable name")
Similar to: userhostaddress,browser,cookies,contenttype,isauthenticated

The Response object terms output data to the client, including outputting data to the browser, redirecting the browser to another URL, or outputting a cookie file to the browser.
Its class name is HttpResponse
Properties and Methods
Write () Send string information to client
Whether the BufferOutput property uses caching
Clear () clears the cache
Flush () forces output cached all data
Redirect () Web page turn to address
End () terminates running of the current page
WriteFile () reads a file and writes to the client output stream
(Essence: Opens the file and outputs it to the client.) )
1.response.write variable data or string
Response.Write (variable data or string)
Response.Write ("<script Language=javascript>alert (' Welcome to study ') </script>")
Response.Write ("<script> (' webform2.aspx ') </script>")
The redirect method of the 2.Response object redirects the client browser to another URL, which is to jump to another page.
For example:
Response.Redirect ("")
3. Response.End () terminates the running of the current page
4.response.writefile (FileName)
FileName refers to the filename of the file that you want to output to the browser

The server object provides access to methods and properties on the server. Its class name is HttpServerUtility.
The main properties of the server object are:
MachineName: Gets the computer name of the server.
ScriptTimeout: Gets and sets the request timeout (in seconds).
Description of Method Name
CreateObject creates a server instance of a COM object.
Execute executes another ASPX page on the current server, finishes the page, and then returns to this page to continue execution
HtmlEncode HTML encoding of the string to be displayed in the browser and returns the encoded string.
HtmlDecode decodes the HTML-encoded string and returns the decoded string.
MapPath returns the physical file path corresponding to the specified virtual path on the WEB server.
Transfer terminates execution of the current page and starts executing a new page for the current request.
UrlEncode encodes a string that represents a URL for a reliable HTTP transmission from the WEB server to the client via a URL.
UrlDecode decodes the URL string that has been encoded and returns the decoded string.
Urlpathencode URL-encodes the path portion of the URL string and returns the encoded string.
Server.HTMLEncode ("HTML code")
Server.htmldecode ("encoded HTML")
The MapPath method of a 1.Server object converts a virtual path or relative path relative to the current page into a physical file path on the Web server.
Syntax: Server.MapPath ("virtual path")
String FilePath
FilePath = Server.MapPath ("/")
Response.Write (FilePath)

The purpose of the Application object in the actual network development is to record the information of the whole network, such as the number of people on line, online list, opinion survey and online election. Share information between multiple users of a given application and persist data during the server's run. The Application object also has the means to control access to the application-tier data and the events that can be used to trigger the process when the application starts and stops.
1. Save information using the Application object
Saving information using the Application object
Application ("key name") = value
Application ("Key Name", value)
Get Application Object Information
Variable name = Application ("Key Name")
OR: Variable name = Application.item ("Key Name")
OR: Variable name = Application.get ("Key Name")
Update the value of the Application object
Application.set ("Key Name", value)
Delete a key
Application.remove ("Key Name", value)
Remove all keys
Application.removeall ()
or Application.clear ()
2. It is possible for multiple users to access the same Application object at the same time. This makes it possible for multiple users to modify the same application named object, resulting in inconsistent data issues.
The HttpApplicationState class provides two methods of Lock and Unlock to resolve access synchronization problems for application objects, allowing only one thread to access the application state variable at a time.
About locking and unlocking
Lock: Application.Lock ()
Access: Application ("key name") = value
Unlocking: Application.UnLock ()
Note: The lock method and the Unlock method should be used in pairs.
can be used for Web site visitors, chat rooms and other equipment
3. Using the Application event
In a application, you can include a special optional file--global.asax file, also known as the application file, that contains the response for ASP. NET or HTTP module is the code of the application-level event that is raised.
The Global.asax file provides 7 events, of which 5 are applied to the Application object

Description of event name
Application_Start fires when the application starts
Application_BeginRequest fires at the start of each request
Application_AuthenticateRequest when attempting to authenticate a consumer
Application_Error fires when an error occurs
Application_End is fired at the end of the application

Session refers to a user's access to a site over a period of time.
The session object corresponds to the HttpSessionState class in. NET, which represents the conversation state, and can hold information related to the current user's session.
The session object is used to store information that is required by a specific user conversation from the beginning of a user's access to a particular ASPX page, until the user leaves. The session object's variables are not purged when the user switches the application's page.
For a Web application, the content of the Application object accessed by all users is exactly the same, while the contents of the session object that are accessed by different user sessions vary. Session can save variables that can only be used by one user, that is, each Web browser has its own session object variable, that is, the session object has uniqueness.
(1) Add a new item to the session state
The syntax format is:
Session ("key name") = value
Session.add ("Key Name", value)
(2) Get the value in session state by name
The syntax format is:
Variable = session ("Key Name")
Variable = session.item ("Key Name")
(3) Delete items in the session-state collection
The syntax format is:
Session.remove ("Key Name")
(4) Clear all values in session state
The syntax format is:
Session.removeall ()
Session.clear ()
(5) Cancel the current session
The syntax format is:
Session.Abandon ()
(6) Set the time-out period for session state, in minutes.
The syntax format is:
Session.Timeout = numeric value
2 events in the Global.asax file are applied to the session object
Description of event name
Session_Start fires when the session is started
Session_End is fired at the end of the session

A cookie is a piece of text that a Web server saves on a user's hard disk. Cookies allow a Web site to save information on a user's computer and then retrieve it. Pieces of information are stored in the form of ' key/value ' pairs.
A cookie is a text file saved on a client's hard disk that stores information about a specific client, session, or application and corresponds to the HttpCookie class in. Net.
There are two types of cookies: Session cookie and persistent cookie. The former is temporary and will cease to exist once the session state ends, while the latter has a definite expiration date, and before expiration the cookie is stored as a text file on the user's computer.
Creating and exporting cookies to the client on the server can be implemented using the response object.
The response object supports a collection called Cookies that can be added to the collection to output cookies to the client.
Access cookies through a collection of cookies from the request object


This chapter describes's built-in objects and the configuration of the application, and in the last section, introduces precompilation and compilation of the Web site. Asp. NET's built-in objects include request, Response, Server, application, session, Cookie, and so on. The configuration part of the application consists primarily of understanding the application configuration, basic configuration elements, configuration and retrieval of custom application settings, and so on. These are described separately below. 14.1 ASP. NET built-in objects

Asp. NET provides a number of built-in objects, one of which is the response object used earlier. These objects provide a considerable amount of functionality, such as passing variables, outputting data, and recording variable values between two Web pages. These objects are already present in the ASP era, and they can still be used in the environment. Moreover, they are more diverse and more powerful.

Asp. NET built-in objects are ActiveX DLL components initialized by the IIS console. Because IIS can initialize these built-in components for, users can also directly reference these components to implement their own programming, which means that they can be referenced in the application to access built-in objects.

This section describes in detail the of these built-in objects, as well as the cache objects and global files. 14.1.1 Response Object

The response object is an instance of the HttpResponse class. This class is primarily to encapsulate HTTP response information from operations. 1. Properties of the Response object

The properties of the response object are shown in table 14-1.

Table 14-1 Properties of Response objects



Property value


Gets or sets a value that indicates whether to buffer the output and send it after the entire page is finished processing

True if the output to the client is buffered, or false. The default is True

Continued form



Property value


Get caching policies for Web pages (expiration, confidentiality, change clauses)

HttpCachePolicy object that contains cached policy information about the current response


Gets or sets the HTTP character set for the output stream

HTTP character set for output stream


Gets a value indicating whether the client is still connected to the server

True if the client is still currently connected; false otherwise

Example 14-1: Using buffers

Because the BufferOutput property of the Response object defaults to True, the data to be exported to the client is temporarily stored in the buffer, and all the data in the buffer is sent to the client's browser until all the event programs and all the page objects have been interpreted. The following example shows how the buffer works.


Response.Write ("Cache cleared" + "<Br>");


<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e)


Response.Write ("before cache clears" + "<Br>");

Response.Clear ();



The above program code instance first gives the "Cache purge before" line in the "Page_Load" event, where the data exists in a buffer. The data of the buffer is then purged using the clear method of the response object, so the string that has just been sent is cleared. IIS then begins to read the portions of the HTML component and sends the results to the client's browser. Only "Cached purge" occurs from the execution result, the data before using the clear method does not appear on the browser, so the program begins with a buffer. If you add "Response.bufferoutput=false" to the same program:


Response.Write ("Data after removal <Br>");


<script language= "C #" runat= "Server" >

void Page_Load (Object sender, EventArgs e)



Response.Write ("Data prior to clearing buffer" + "<Br>");

Response.Clear ();



As you can see, the results of the execution do not erase the data of the buffer by using the Clear method, which indicates that the data is output directly and not stored in the buffer. 2. Methods of response Objects

The response object can output information to the client, including sending information directly to the browser, redirecting the browser to another URL, or setting the value of the cookie. Table 14-2 lists several common methods.

Table 14-2 Methods for response objects




Writes the result of the specified string or expression to the current HTTP output


Stop the page from executing and get the results


Used to empty the cache of the current page without outputting the contents of the cache, the clear method can be used only if the cached output is used


Displays the contents of the cache immediately. The method has one point, like the clear method, that fails before the script sets the buffer property to True. Unlike the end method, after the method is called, the page can continue to execute


Causes the browser to immediately redirect to the URL specified by the program

Asp. NET, the syntax for referencing object methods is "object name. Method Name." A "method" is a program code embedded in an object definition that defines how an object handles information. Using an embedded method, the object knows how to perform the task without providing additional instructions. Here are a few small examples to explain the common methods of response objects.

Example 14-2: Use Response.Write to send information to the client

for (int i=1;i<=500;i++)


Response.Write ("i=" +i+ "<BR>");


This example uses the "write" method to output 500 values to the screen.

Example 14-3: Using the Response.End method to debug a program

The end method can stop the execution of the current page and, for this reason, can be combined with the Response.Write method to output a variable, array value on the current page.

<form id= "Form1" method= "POST" runat= "Server" >

Enter a value: <asp:textbox id= "Txtvar" runat= "Server" ></asp:TextBox>

<asp:button id= "btnsubmit" runat= "Server" text= "calculates the square value of this value" onclick= "btnSubmit_Click" ></asp:Button>


<script language= "C #" runat= "Server" >

void btnSubmit_Click (Object sender, EventArgs e)


int N = Int. Parse (request.form["Txtvar"). ToString ());

Response.Write ("n=" + N + "<br>");

Response.Write ("The square value of this value is:" + n*n);



Run the above code, and the result is as shown in Figure 14-1.

Figure 14-1 Using the Response.End debug program

Enter a value of "6" and click the "Calculate the square value of this value" button, and the screen will display the following results:


The square value of this value is: 36

Add "Response.End ()" to your code as follows:

<script language= "C #" runat= "Server" >

void btnSubmit_Click (Object sender, EventArgs e)


int N = Int. Parse (request.form["Txtvar"). ToString ());

Response.Write ("n=" + N + "<br>");

Response.End ();

Response.Write ("The square value of this value is:" + n*n);



Then run the code and it will only show:


The experiment proves that the "Response.End ()" Method stops the execution of the current page. This is just a small example, and the reader can then use the End method in the program to debug. But remember to debug the code, do not forget to debug the "Response.End ()" deleted.

Example 14-4: page redirection using the Redirect method

In web programming, you often encounter situations where a program performs a page transfer to a location. The Response.Redirect method can satisfy this requirement, such as code:

Response.Redirect ("");

To execute the code, the page will jump to NetEase 163 's homepage. 14.1.2 Request Object

The request object is an instance of the HttpRequest class. It can read the HTTP values that the client sends during a Web request. 1. Properties of the Request object

The properties of the request object are shown in table 14-3.

Table 14-3 The properties of the Request object


Property value


Get HTTP query string variable collection

NameValueCollection Object


Get the virtual path for the current request

The current request virtual path


Get remote client IP host address

Remote Client IP address

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: 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.