Six built-in objects of ASP. NET

Source: Internet
Author: User

ASP. NET built-in object
1. Response object

The response object is an instance of the httpresponse class. This class encapsulates HTTP Response Information from ASP. NET operations.

1. attributes of the response object

(1) contenttype attribute. The contenttype attribute specifies the HTTP content type of the response. If contenttype is not specified, the default value is text/html.
(2) charset attributes. The charset attribute attaches the character set name to the Content-Type header of the response object. For

On the ASP. NET page, the Content-Type header is Content-Type: text/html. You can specify the Content-Type header information in the ASP file, for example:
Response. charset = "gb2312 ";
The following results are generated:
Content-Type: text/html; charset = gb2312
This function inserts a string into the Content-Type Header regardless of whether the character set is valid. If a page contains multiple tags containing response. charset

Each response. charset replaces the previous charsetname. In this way, the character set is set to the value specified by the last instance of response. charset on this page.
(3) expires attributes. The expires attribute specifies the time before the page cached on the browser expires. If you return to this page before a page expires

The version in the buffer. If response. expires is set to 0, the cached page can expire immediately. This is a more practical attribute. When the customer enters the web site through the ASP. NET login page

This attribute should be used to immediately expire the logon page to ensure security.
(4) expiresabsolute attribute. Unlike the expires attribute, the expiresabsolute attribute specifies the exact expiration date and time of the page cached in the browser. Before Expiration

If the user returns to the page, the page in the cache is displayed. If no time is specified, the home page will expire at midnight that day. If no date is specified

Expiration time.

2. Response object Method

The response object can output information to the client, including sending the information directly to the browser, redirecting the browser to another URL, or setting the cookie value.

1. Write Method
ASP. the syntax for referencing object methods in. NET is "Object Name. method Name, as shown in response in the following script. write (I + "<br>") Statement, which means to reference

The write method is displayed from 1 to 500 on the screen. After each command is executed, the result is immediately displayed, and the execution result is displayed in real time.
For (INT I = 1; I <= 500; I ++)
{
Response. Write (I + "<br> ");
}
The write method of the response object writes the result of the specified string or expression to the current HTTP output. The method is embedded into the program code in the object definition, which defines how the object goes

Process information. With the embedded method, the object knows how to execute the task without providing additional instructions.

2. bufferoutput related methods
In some cases, the execution process can be continued using the Buffer Zone. When the buffer zone is used, the results will not be output to the browser until the execution of the entire page ends. The buffer method has been disabled.

Instead, the bufferoutput method is provided to be compatible with the previous ASP version. Use bufferoutput in ASP. NET. If the output to the client is buffered

True; otherwise, false. The default value is true.
The following example only performs operations when the output is buffered.
If (response. bufferoutput = true)
{
//....
}
3. End method, clear method, and flush Method
The response object also has the end method and the clear method. The end method immediately stops page execution and obtains corresponding results. When executing the end method, you do not need to consider whether the cache has been lost.

Output. In addition, the end method is very useful in program debugging. It can output part of the content to help determine where the program is aborted or failed.
The clear method is used to clear the cache of the current page without outputting the cached content. The clear method can be used only when the cached output is used.
The response object is in the cache output. Another method is flush, which can display the cached content immediately. This method is the same as the clear method.

An error occurs when the buffer attribute is not set to true. Unlike the end method, this page can be executed after the method is called.

4. Redirect Method
Another common method of object response is the Redirect method. In many cases, the website needs to direct the user to another homepage. For example, the user registration form is not filled completely or

If an error is entered, the submitter automatically returns the user to the registration page. The redirect method redirects the browser to the URL specified by the program immediately. This is also a development phase

This way, programmers can specify different pages for different customers or different pages according to different situations based on different responses. Once used

Redirect method, any response body content explicitly set on the page will be ignored. However, this method generates

The redirected URL is used as the automatic response body of the link.
You can use the response. Redirect method to point to any legal website, which can be an HTML page or ASPX page, or be on the current server or LAN

To any server that comes with the operating system and httpserver on the wide area network.
However, the current operation is not smooth, and the old version of the browser is usually unable to process, but will display the following information:
Object Moved
This object may be found here
Click here to go to the corresponding page.
In this way, the user experience is not very good. Therefore, you can include the page to be transferred to the current file. The include command on the server can easily include other

File. This server-side include command does not need to be implemented in the script. It can be used as part of HTML code, for example:
<HTML>
<Head> <title> welcome </title> <Body>
<! -- # Include virtual = "mybanner. Inc" -->
Welcome to the file inclusion example Program
</Body>
</Html>
In this example. The mybanner. inc file will be inserted under the <body> mark of the ASP. NET file. When the ASP. NET file is executed, the HTML code in mybanner. inc

And the script will also be executed or appear in the corresponding location. This file package contains two paths: virtual path or physical path. The following is an example of a physical path:
<HTML>
<Head> <title> welcome </title> <! -- # Include file = "mybanner. Inc" -->
Welcome to the file inclusion example Program
</Body>
</Html>
If you use the file command to specify the physical path, the file must be in the current directory or subdirectory. In this example, the file is in the current directory, so there are many restrictions.

Generally, the virtual path command should be used.
This type of file is valid for any other extension. Generally, it is used to the. inc extension, but aspx, htm, HTML, or any other extension can also be used. There are two types

In this case, you need to include other files. One is that there are some common program segments or scripts that do not need to be written every ASP. NET file.

Only include ASP. NET files.

Ii. Request object

The request object is an instance of the httprequest class. Enable ASP. NET to read the HTTP value sent by the client during the Web request.

1. attributes of the request object

(1) totalbytes attributes
Obtain the total number of bytes sent by the client in the Request body. This attribute is read-only.
Syntax: Counter = request. totalbytes;
(2) Counter attributes
Specify a variable to receive the total number of bytes sent by the client in the request.

2. Method of the request object

(1) form and querystring Methods
When you need to transmit messages in multiple ASP. NET homepages, the form method of the request is a selectable method. It sends an HTTP request through table search using the POST method

The value of the table element in the body.
The form set is indexed by the parameter names in the Request body. The value of request. Form (element) is the element value in the Request body.
In the request object, there is also a set that implements similar functions, which is querystring. You can often see network addresses like this:

"Http://www.ECNU.com/query.asp? Stockcode = 06601"
Question mark (?) The following value is the HTTP query string, while the querystring collection retrieves the value of the variable in the HTTP query string. Send table data or

Enter a query string in the address box to generate a similar query string. The difference between it and the form set is that when the querystring set is used to retrieve the value of the variable in the HTTP query string, the variable and its value are

Visible. That is to say, any passing person can see the value of any variable received by the querystring set, which means it is very dangerous to use it to pass the user password.
If the transferred data volume is large, it is difficult to use the query field. For different browsers, the size of the information transmitted varies. For example, some browsers cannot process

Query fields that exceed 2000 characters. If the length of the query field in the URL Connection exceeds this length, the browser cannot correctly process the query field. Sometimes the length of a field cannot be determined because

The length restricted by the browser is the maximum length that can be displayed and sent in the browser's address bar, that is, the total length of the URL address and query field. Generally, if the transfer data volume ratio

If it is large, do not use this method. Therefore, the information transmitted using the query field should be concise and non-confidential. If a large amount of data needs to be transferred, you can use HTTP

For more information about the hidden type in form, see Introduction to HTML. It is worth noting that the HTTP protocol is much more effective when passing a form than when passing a query field.
(2) binaryread Method
The request object includes the binaryread method, which obtains the data transmitted from the client to the server as part of the POST request.
Syntax: variant = request. binaryread (count)
Parameters:
· Variant: An array containing the unsigned number returned by this method. The parameter type is byte.
· Count: specify the number of bytes to be read from the client before execution. After this method is returned, count will contain the number of bytes successfully read from the client. The total number of bytes actually read will be smaller

Or equal to request. totalbytes.
The binaryread method is used to read unprocessed data sent from the client as part of a POST request. This method is used to access data at the underlying layer. In contrast, the request. Form set

Used to view the table data sent in the announcement request. Once binaryread is called, any variables referenced in the request. Form set will cause an error. Otherwise

In the request. Form set, calling binarywrite will also cause an error. Remember, if the variable in the request set is not specified

A subset that searches for the request. Form set and enforces the above rules.

3. Application Object

The application object is an instance of the httpapplicationstate class.
A single instance of the httpapplicationstate class is created when the client requests any URL resource from a specific virtual directory of an ASP. NET application for the first time. For

Each ASP. NET application must create a separate instance. Then, the reference to each instance is made public through the internal application object.
· Data can be shared within the application object. Therefore, an application object can overwrite multiple users.
· An application object containing events can trigger some application object scripts.
· Individual application objects can be set using Internet Service Manager to obtain different attributes.
· Individual application objects can be isolated and run in their own memory. That is to say, if a person's application is damaged, it will not affect others.
· You can stop an Application Object (removing all its components from the memory) without affecting other applications.
A website can have more than one application object. In typical cases, you can create individual application objects for some files of a specific task. For example, you can create

Application object to apply to all public users, and then create another application object only applies to the network administrator.
The application object allows all users of a given application to share information and persistently save data during server running. Because multiple users can share one

Application object, so you must have the lock and Unlock methods to ensure that multiple users cannot change a certain attribute at the same time.

1. Set of application objects

(1) contents set. The following example creates a new httpapplicationstate object, which is used to access the object name in the application state set.
Httpapplicationstate appstate2;
Appstate2 = application. contents;
String [] statevars = new string [appstate2.count];
Statevars = appstate2.allkeys;
(2) staticobjects set. The staticobject set contains all objects created using the <Object> flag in the Application object range. You can use this set to determine a pair

Such as the value or traversal set of the specified attribute, and retrieving all attributes of all static objects.
Syntax:
Public httpstaticobjectcollection staticobjects {Get ;}
The loop control structure can be used to traverse the keywords in the staticobjects set. See the following example.
Httpstaticobjectscollection pageobjects;
Pageobjects = application. staticobjects;
If (pageobjects. Count> 0)
{
//...
}

2. Method of Application Object

(1) Lock method. The lock method prevents other customers from modifying the variables stored in the Application object, so that only one customer can modify and access the variables at the same time.

Application variable. If you do not explicitly call the unlock method, the server will unlock the application object after the page file ends or times out.
Syntax: Public void lock ();
(2) Unlock method. The unlock method allows other clients to modify the variables stored in the Application object after locking the Application Object using the lock method. If not displayed, call

Method, the web server will unlock the application object after the page file ends or times out.
Syntax: Public void unlock ();
The following example uses the lock and Unlock methods to prevent other sessions from changing the values of the two Application variables before the local session changes them.
Application. Lock ();
Application ["mycode"] = 21;
Application ["mycount"] = convert. toint32 (application ["mycount"]) + 1;
Application. Unlock ();

3. Application Object events

(1) application_onend event. The application_onend event occurs after the session_onend event when the application exits. Only

Images are available.
(2) application_onstart event. The application_onstart event occurs before a new session (session_onstart event) is created for the first time. Only application and

Server embedded objects are available. Referencing the session, request, or response object in the application_onstart event script will cause an error.
The onstart event of an Application object must occur before the session_start event. However, the application object is not requested by a new user as the session object.

The application object is triggered only once, that is, the first request of the first user.
Application_onend event is triggered only when the service is terminated or the application object is uninstalled. For example, if the network service is disabled in Internet Service Manager

Application_onend event will be triggered. If you use application for a separate purpose, this event can be triggered when the application is uninstalled using the unload button.

. An application_onend event must occur after the session_onend event.
Application_onstart and application_onend events are the only scripts that are triggered. All these events are in a file, that is, the global. asax file.
It should be noted that because the application object is shared by multiple users, it is essentially different from the session object. At the same time, the application object will not be

Once an application object is created, it will always exist until the website is closed or the application object is uninstalled. This can often be weeks or

Several months.
Because the application object will not be deregistered after it is created, it must be used with special care, it will occupy the memory, you need to consider the use of so as not to reduce the server's response speed to other work

. There are three methods to abort an application object: service suspension, global. asax change, or the application object is uninstalled.

Iv. Session Object

The Session object is an instance of httpsessionstate. This class provides information for the current user session, and also provides access to the cache of the session range that can be used to store information, as well as control

How to manage sessions.
The invention of session is to fill in the limitations of the HTTP protocol. The HTTP protocol works in the process that the user sends a request and the server responds. The connection between the client and the server is

Scattered, non-consecutive. There is nothing in the HTTP protocol that allows the server side to track user requests. After the server completes the response to the user's request, the server cannot continue

The browser maintains the connection. From the website's point of view, each new request exists independently. Therefore, a user cannot know his/her identity when switching between multiple home pages.
The Session object can be used to store the information required for a specific user session. In this way, the variables stored in the session object will not be lost when the user jumps between the web pages of the application.

, But continues to exist throughout the user session.
When a user requests a web page from an application, if the user does not have a session, the web server automatically creates a session object. When the session expires or is abandoned

Stop the session.
When the user requests the aspx file in the given application for the first time, ASP. NET generates a sessionid. Sessionid is a number generated by a complex algorithm, which uniquely identifies each

User sessions. When a new session starts, the server stores the sessionid as a cookie in your web browser.
After the sessionid cookie is stored in the user's browser, even if the user requests another. aspx file or requests the. aspx file that runs in another application,

ASP. NET will still reuse this cookie to trace sessions. Similarly, if the user deliberately abandons the session or causes the session to time out and then requests another. aspx file, ASP. NET will use the same

Cookie starts a new session. The sessionid settings stored in the memory are cleared only when the server administrator restarts the server or the user restarts the web browser.

The user will obtain the new sessionid cookie.
By reusing the sessionid cookie, the Web application minimizes the number of cookies sent to the user's browser. In addition, if you decide that the Web application does not require session management

To prevent Web applications from tracking sessions and sending sessionids to users.
The most common usage of session objects is to store users' preferences. For example, if you specify that you do not like to view images, it is also often used in programs that identify customers.

Note that the session status is retained only in the browser that supports cookies. If the cookie option is disabled, the session cannot be used.
ASP. NET sessions are very useful and can be fully controlled by session objects. If you need to store information in a user session, you only need to directly call

You can use the session object. The following is an example:
Session ("myname") = response. Form ("username ");
Session ("mycompany") = response. Form ("usercompany ");
Generally, you cannot use common script variables for this processing, because the common variables are only valid on a single homepage, and session variables exist until the user leaves the website.

.
It should be noted that session objects are associated with specific users. The Session Object assigned to a user is completely independent from the session objects of other users and will not affect each other.

. In other words, the information stored for each user is exclusive to each user and will not be shared.
Obviously, for different users, the myname variable and mycompany variable of the session object are different. when each person browses between different homepage of the website

The variables will be retained, which is very effective as identity authentication.

1. Set of session objects

(1) contents set
The session. Contents set includes all the items created for the session without the <Object> flag. This set can be used to determine the value of a specified session item or traverse the set and retrieve the session

List of all items.
Syntax: Public httpsessionstate contents {Get ;}
(2) staticobjects set
The staticobject set contains all the objects created with the <Object> mark in the range of session objects. This set can be used to determine the value of a specific object attribute, or to traverse the set and obtain

All attributes of an object.
Syntax: Public httpstaticobjectscollection staticobjects {Get ;}

2. attributes of the Session Object

(1) sessionid attributes
The sessionid attribute returns the user's session identifier. When creating a session, the server generates a separate identifier for each session. The session identifier is returned as a long integer.

In many cases, sessionid can be used for web page registration statistics.
Do not use the sessionid attribute to create primary keywords for database applications. This is because if the web server is restarted, some sessionid values may be generated before the server is terminated.

. You can use the column data types that are automatically added, such as identity in SQL Server or counter in access.
(2) Timeout attribute
How does the server know that a session object is over? In other words, how do you know whether the user has left the site and has gone to another site or has switched off the computer? For example

If a user does not make a request or refresh the homepage for 20 minutes, the server will leave by default. This policy allows the server to release user processes.

The resource used for tracking.
For some network sites, 20 minutes is obviously short. For example, it takes a long time to consider network go. If resources are released in 20 minutes, the player will be attacked by the server.

Terminal "boom ".
On the contrary, some network sites have limited resources and a large amount of access traffic, so there is no time-consuming information transmission. It is a pity to waste resources and it will make other visitors

The access speed is affected.
However, for ASP. NET, there is no difficulty in controlling these items. The session object has this timeout attribute, and you can use the session object to limit the time.

3. Method of Session Object

There is an abandon method in the session object method. This method can delete all objects stored in the session object and release the resources of these objects. If not explicitly called

The server will delete these objects once the session times out.
Syntax: Public void abandon ();
When the abandon method is called, the current session object will be deleted in sequence. However, after all script commands on the current page are processed, the object will be deleted. That is to say, in

When you call abandon, you can access the variables stored in the session object on the current page, but not on subsequent web pages. When the server finishes processing the current page, the following example will release

Session object Resources:
Session. Abandon ();
When the user's session time expires, if the user refreshes the home page, the user will be considered as a new visitor, and all the previous session information will be lost. You can also use

Abandon method to cancel a session. Here we introduce another sessionid attribute. This attribute will automatically assign different numbers to each session.
It should be noted that for a session object, no matter how the user switches between the home pages, there can only be one sessionid. However, because the abandon method is used

This enables the home page to be deleted immediately after a session is opened, and then another one. For the server side, it is two different session objects, the previous one is closed, and then

.

4. Session Object events

(1) session_onend event. The session_onend event occurs when the session is abandoned or timed out. Only application, server, and session objects are available in server embedded objects.

.
(2) session_onstart event. Session_onstart event occurs when the server creates a new session. The server processes the script before executing the request page. Session_onstart

Events are the best time to set session variables, because they are set before accessing any page.
The session_onstart event and session_onend event scripts are located in the specified file global. asax.

V. Server objects

The server object is an instance of httpserverutility. This object provides access to methods and properties on the server.

1. Server Object Attributes

The server object contains the scripttimeout attribute.
The scripttimeout attribute specifies the maximum time that a script can run before it ends. When processing server components, the timeout limit does not take effect.
Syntax: Public int scripttimeout {Get; set ;}
Parameter: numseconds specifies the maximum number of seconds that a script can run before the end of the server. The default value is 90 seconds.
When the script developed by the user generates a very huge homepage, the user certainly does not want the homepage to be half displayed and it times out. The scripttimeout of the server object can be used.

A reasonable time limit for Attribute customization is as follows: Server. scripttimeout = 150;

2. Server Object Method

(1) creatobject method. Server. Createobject is used to create ActiveX component instances registered on the server. This is a very important feature, because

ActiveX components can easily expand ActiveX capabilities, such as database connections, file access, and advertisement display capabilities.

Yes.
This method has been overloaded. The syntax is as follows:
Create a server instance of a COM object. The COM object is identified by the program ID of the object.
Public object Createobject (string );
Creates a server instance of the COM Object identified by the object type.
Public object Createobject (type );
By default, the object created by the server. Createobject method has a page scope. This means that after the current ASP. NET page is processed, the server will automatically destroy these

Image. If you want to create an object with a session or application scope, you can use <Object> to mark and set the scope attribute of the session or application object, or in the dialog and Application

This object is stored in program variables:
Session ("ad") = server. Createobject ("mswc. adrotator ");
Note that you cannot create an object instance with the same name as the embedded object. Otherwise, the following script will return an error message:
Response = server. Createobject ("response ");
(2) htmlencode method. The htmlencode method allows HTML encoding of specific strings. Although HTML can display most of the text written into ASP. NET files

If you want to actually include the characters used in the HTML Tag, you will encounter problems. This is because when the browser reads such a string, it tries to explain it.
Encode the string in HTML format and return the encoded string.
Public String htmlencode (string );
Encode the string in HTML format and send the result output to the textwriter output stream.
Public void htmlencode (string, textwriter );
For example, if you want to explain <br> A line break will be generated in an HTML file, you may write as follows:
<HTML>
<Body>
<Font size = 3> in HTML, the symbol <br> performs a line feed operation </font>
</Body>
</Html>
The browser displays:
In HTML, the symbol
Line feed will be performed
The running result of the preceding statement does not show the user's imagination. To avoid such problems, you need to use the htmlencode method of the server object and use the corresponding solution that cannot be solved by the browser.

The interpreted HTML encoding replaces the HTML markup characters. Therefore, only the following code can display the correct htmlencode string and output the text as needed in the browser.
Response. Write (server. htmlencode ("in HTML, the symbol <br> will be used for line feed "));
The preceding statement is displayed in the browser:
In HTML, the symbol <br> performs a line feed operation.
(3) urlencode method. Just as the htmlencode method enables the customer to translate strings into an acceptable HTML format, the urlencode method of the server object can follow the URL rules

Encode the string correctly. When string data is transmitted to the server as a URL, spaces or special characters are not allowed in the string. To do this, if you want

You can use the server. urlencode method to encode the URL before sending a string.
This function has been overloaded. The syntax is as follows:
Encode the string and return the encoded string.
Public String urlencode (string );
The URL encodes the string and sends the result output to the textwriter output stream.
Public void urlencode (string, textwriter );
For example:
<% Response. Write (server. urlencode ("Http://www.microsoft.com ") %>
Generate the following output:
HTTP % 3A % 2 fwww % 2 emicrosoft % 2 ECOM
When querystring is used to transmit information between different homepages, if the information contains spaces or special characters, encode must be performed, because if this is not done, it is likely that

The information side receives some unexpected strange strings. Do not perform the encode operation on the name and equal sign of querystring. You only need to encode the value of querystring.

.
After the encode operation, the effect is as follows:
Message = This + query + String + has + been + URL + encoded % 2e
The user does not need to consider decoding the above string and will perform such processing automatically. For example, suppose there is a script like this:
Request. querystring ("message ");
The result is as follows:
This query string has been URL encoded
(4) mappath method. The mappath method maps the specified relative or virtual path to the corresponding physical directory on the server.
Syntax: Public String mappath (string path );
The path parameter specifies the relative or virtual path to map to the physical directory. If the path starts with a forward slash (/) or backslash (/), the mappath method regards the path as complete when returning the path.

. If the path does not start with a slash, The mappath method returns the path relative to the existing path in the page file. Note that the mappath method does not check the returned results.

Whether the path is correct or whether it exists on the server.
For the example below, the data.txt file and the test. aspx file containing the following scripts are all in the directory c:/inetpub/wwwroot/Aspx. C:/inetpub/wwwroot directory is set

The Home Directory of the server. The following example uses the server variable path_info to map the physical path of the current file. The following script:
Server. mappath (request. servervariables ("path_info "));
Output: C:/inetpub/wwwroot/asp/test. aspx
Because the path parameters in the following example do not start with a slash, they are relatively mapped to the current directory, which is the directory c:/inetpub/wwwroot/Aspx. The following script:
Server. mappath ("data.txt ");
Server. mappath ("aspx/data.txt ");
Output:
C:/inetpub/wwwroot/aspx/data.txt
C:/inetpub/wwwroot/aspx/data.txt

(6) Cookie
A cookie is a piece of text that the Web server saves on the user's hard disk. Cookie allows a Web site to save information on a user's computer and then retrieve it. The piece of information uses the 'key/

Stored as a value pair.

Cookie is a text file stored on the client's hard disk. It can store information about a specific client, session, or application. It corresponds to the httpcookie class in. net.

There are two types of cookies: Session Cookie and persistent cookie. The former is temporary. Once the session state ends, it will no longer exist.

Before the expiration date, the cookie is stored as a text file on the user's computer.

You can use the response object to create a cookie on the server and output it to the client.

The response object supports a set named cookies. You can add cookie objects to the set to output cookies to the client.

Access the cookie through the cookie set of the request 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.