Asp.net built-in object

Source: Internet
Author: User
1. Response object

The response object is an instance of the httpresponse class. This class is mainly encapsulated fromASP. NETThe HTTP Response Information of the operation.

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. ForASP. NETPage, 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 zone is displayed. If response. expires is set to 0, the cached page can expire immediately. This is a more practical attribute, when the customer passesASP. NETTo 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. If you return to this page before expiration, 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, the home page will expire at the specified time on the day when the script runs.

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. NETThe syntax for referencing object methods in is "Object Name. method Name, as shown in response in the following script. write (I + "<br>") Statement, which means that the write method that references the response object 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 processes 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 rejected. Instead, the bufferoutput method is provided to be compatible with the previous ASP version. InASP. NETUse bufferoutput. True if the output to the client is buffered; 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 cache output is performed. 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. If the buffer attribute is not set to true before the script, an error occurs. 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 submitted if it is not filled in completely or incorrect, 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 frequently used method during development. In this way, programmers can specify different pages for different customers or different pages based on different situations based on different responses. Once the Redirect method is used, any response body content explicitly set on the page will be ignored. However, this method does not send other HTTP header information set for this page to the client, but generates an automatic response body that uses the redirected URL as the link.
Response. the redirect method is used to direct to any valid website. The URL can be an HTML page or An ASPX page, and can be on the current server, it can also be a local area network or even any server with its own operating system and httpserver.
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 be easily used inASP. NETContains other files. 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 to thisASP. NET<Body> mark the following file.ASP. NETWhen the file is executed, the HTML code and script in mybanner. Inc 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. Therefore, you should generally use the virtual path command.
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 situations where you need to include other files. One is that there are some common program segments or scripts that do not require eachASP. NETThe file can be written onceASP. NETFile.

Ii. Request object

The request object is an instance of the httprequest class. EnableASP. NETCan 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 multipleASP. NETWhen a message is transmitted on the homepage, the form method of the request is optional. It transmits the values of table elements to the HTTP Request body through table retrieval using the POST method.
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. We often see such a network address: "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. Similar query strings can be generated by sending table data or entering a query in the address box of the browser. 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 maximum length that can be displayed and sent in the address bar of the browser is the maximum length of the URL address and the total length of the query field. Generally, this method is not recommended if the transferred data volume is large. 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 the hidden type in the HTTP form, for more information, 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 less than 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 is 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, once a variable in the request. Form set is referenced, calling binarywrite will also cause an error. Remember, if you do not specify the subset of the variable when accessing the variable in the request set, you will search for the request. Form set and force the above rules to use.

3. Application Object

The application object is an instance of the httpapplicationstate class.
For a single instance of the httpapplicationstate classASP. NETIt is created when any URL resource is requested in the application virtual directory. For eachASP. NETEach 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 an application object for all public users, and then create another application object for only 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 an application object, the lock and Unlock methods must be available 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 the value of a specified property of an object or traverse the set, and retrieve 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 Application variables at the same time. 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 this method is not displayed, 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 the embedded applicaiton and server objects 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 triggered after a new user request, as the session object does. The application object is only triggered once, that is, the first request of the first user.
The application_onend event is triggered only when the service is suspended or the application object is uninstalled. For example, if the network service is disabled in Internet Service Manager, The application_onend event is triggered, if the application is used 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 disappear because one or even all users leave. Once an application object is created, it will always exist until the website is closed or the application object is uninstalled. This may often take weeks or 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. It also provides access to the cache of the session range that can be used to store information, and controls how to manage sessions.
The invention of session is to fill in the limitations of the HTTP protocol. During the HTTP protocol operation, the user sends a request and the server responds. The connection between the client and the server is discrete, non-consecutive. There is nothing in the HTTP protocol that allows the server side to track user requests. After the server responds to the user's request, the server cannot continue to connect to the browser. 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, when a user redirects between the web pages of an application, the variables stored in the session object will not be lost, but will continue 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 a session expires or is abandoned, the server suspends the session.
When the user requests the aspx file in the given application for the first time,ASP. NETA sessionid is generated. Sessionid is a number generated by a complex algorithm, which uniquely identifies each user session. 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. NETThe cookie will still be reused to track sessions. Similarly, if the user deliberately abandons the session or causes the session to time out and then requests another. aspx fileASP. NETStarts a new session with the same cookie. Only when the server administrator restarts the server or the user restarts the web browser, the sessionid settings stored in the memory will be cleared. 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, you can prevent the web application 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. NETThe Session object can be used to fully control the session. to store information in a user's session, simply call the session object directly, the following is an example:
Session ("myname") = response. Form ("username ");
Session ("mycompany") = response. Form ("usercompany ");
Generally, you cannot use common script variables for such processing, because common variables are only valid on a single homepage, and session variables exist and take effect 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 does 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 user browses between different homepage of the website, such individual 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 list of all items in the session.
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 the attributes of all objects.
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, the values of some sessionids may be the same as those 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? If a person has not made a request or refreshed the homepage for 20 minutes, the server will default that the user has left. This policy allows the server to release resources used for tracking user processes.
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 ".
On the contrary, some network sites have limited resources and a large amount of access traffic, and there is no time-consuming information transmission. It is a pity that resources are wasted, the access speed of other visitors is also affected.
However,ASP. NETIt is not difficult to control these attributes. The session object has this timeout attribute, so 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 the abandon method is 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. This means that when you call abandon, you can access the variables stored in the session object on the current page, but not on the subsequent web pages. When the server finishes processing the current page, the following example releases the session object Resource:
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 the 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 in this case, a session is opened on the home page and then eliminated. For the server side, it is two different session objects, the previous one has been disabled, and the subsequent one remains unchanged.

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-period 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. You can use the scripttimeout attribute of the server object to customize a reasonable time limit, as shown below: 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 capabilities can be easily expanded by using ActiveX components, for example, database connections, file access, and Ad display cannot provide or simply rely on the functions that ActiveX alone can do.
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. That is to say, in the currentASP. NETAfter the page is processed, the server automatically destroys these objects. 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, you can also store the object in the dialog and Application 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 data writtenASP. NETFile, but when you need to actually contain 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 HTML encoding that is not interpreted by the browser to replace 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 acceptable HTML formats, the urlencode method of the server object can correctly encode strings according to URL rules. When string data is transmitted to the server as a URL, spaces or special characters are not allowed in the string. To do this, you can use the server. urlencode method to encode the URL before sending the 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 recipient 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 a complete virtual path 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 whether the returned 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 as the host 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
 

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.