System. Web Overview:
System. web is. net, which defines all the operation methods between the browser and the server, including the request input stream (httprequest), the output stream (httpresponse), and the context management class (httpcontext) the class associated with the HTTP request.
Only after the system. Web namespace is referenced can developers process HTTP request-related information in the program. The code for referencing a namespace is as follows. "using" is the keyword for loading a namespace, followed by the full name of the namespace.
Using system. Web;
HTTP information set sent by the Client: httprequest class
The httprequest class manages the HTTP information set sent by the client, including cookies, HTTP header information, and subject information. Through the Browse attribute of httprequest, you can also obtain some basic information about the client browser.
Httprequest can also log on to other servers on the network, and then obtain information about other websites through http based on other network operations. This is particularly important for future Web service applications.
Syntax definition
The definition of the httprequest class is very simple. The syntax is defined as follows:
Public sealed class httprequest
The syntax of the constructor using the httprequest class is as follows:
Public httprequest (string filename, string URL, string querystring)
The parameter "FILENAME" indicates the detailed path of the requested file.
The parameter "url" indicates the name of the current request URL.
The "querystring" parameter indicates the requested variable. It indicates "?" In the requested URL. All variables
In actual applications, you do not need to create your own httprequest instance because its method and attributes are provided by the request attributes of other classes (such as page and httpcontext.
Detailed description
The httprequest class is mainly used to obtain the information of HTTP requests. Therefore, there are many required attributes, and the methods are mainly required for conversion. The following describes common methods and descriptions in the httprequest class.
Binaryread: reads the current input stream in binary format.
Mappath: ing between virtual paths and physical paths
Saveas: Save the HTTP request to the disk
Validateinput: Verify the accessed Data
Typical applications:
The httprequest class does not need to be specifically instantiated. Instead, it uses the request attributes of the page and httpcontext classes to implement its basic methods and attributes. This example uses the request attribute of the page class to complete the httprequest class instance.
Response. write ("parameter value:" + request. querystring ["name"] + "<br/>"); obtain the parameters passed on the page and display response. write ("current URL:" + request. URL + "<br/>"); // obtain the current urlresponse. write ("Client IP:" + request. userhostaddress + "<br/>"); // obtain the client's ipresponse. write ("Byte digit of the input stream:" + request. totalbytes + "<br/>"); // obtain the total number of bytes of the input stream. write ("server's first key:" + request. servervariables. allkeys [0] + "<br/>"); // obtain the first request variable in the server variable set. saveas (@ "C: \ test.txt", true); // the request sent from the page is saved in the file.
My personal summary: The httprequest class is a request class, which contains manyHTTP Request InformationThis class can be the encapsulation body of the information. We can use the httprequest class to access the request information, such as request. url and request. querystring ["name.
HTTP message returned by the server: httpreponse
The httpreponse class manages the server's response to HTTP requests and provides methods and attributes to operate the returned data. In practical applications, httprepsonse classes are generally not instantiated, but are obtained through the request attributes such as page and httpcontext, which is the same as the httprequest class.
Syntax definition:
The syntax of the httpresponse class is defined as follows:
Public sealed class httpreponse
The constructor using the httpresponse class is as follows:
Public httpreponse (textwriter writer)
The writer parameter indicates the character editor of the output content.
Attribute details:
The httpresponse class contains many very important application attributes, such as the buffer and buffer configurations of the current server. These attributes and their descriptions are listed below:
Buffer: whether to buffer the output. The output is sent after the response is completed.
Bufferoutput: Indicates whether to buffer the output. After the page is completed, it is sent again.
Cache: Cache Policy for Web pages
Charset: sets the HTTP Character Set of the output stream.
Contentencoding: stream content encoding format
Contenttype: http mime type of the Control Flow
Cookies: Cookie set for response
Expires: Get the cache expiration time
Detailed solution:
The httprepsonse class is mainly used to encapsulate HTTP response information. As some buffer configurations are involved, a lot of cache processing is added to the method. This is very important in C #2.0, because the cache technology is the key to improving web performance. The following describes common methods in the httpresponse class:
Typical application: Use httpresponse to export webpage content to word
Using httpresponse's write method and binarywrite method, you can use httpresponse to easily export webpages, including exporting them to PDF, word, and excel. The binarywrite method is generally used to export image files, while the write method is mainly used to export common strings. The function of this example is to use the write method to export the content of the text box to the word. This function is usually used in the text editor.
Response. clear (); // clear irrelevant information response. buffer = true; // send The Repsonse after completing the response. charset = "gb2312"; // set the character set of the output stream: Chinese response. appendheader ("content-disposition", "attachment?filename=report.doc"); // append header information response. contentencoding = system. text. encoding. getencoding ("gb2312"); // sets the output stream Character Set response. contenttype = "application/MS-word"; // The MIME type response of the output stream. write (textbox1.text); response. end (); // stop the output.
Application Status: httpapplicationstate class
The httpapplicationstate class manages information shared by all sessions, that is, information at the application domain level. All sessions that access the application can access this information. It can be said that the httpapplicationstate class is a data repository that stores information in the memory of the server. This ensures the Data Reading speed. The httpapplicationstate class mainly reads and stores data through its internal object "application". The type of the stored data is "object", and the correct type conversion is required during reading.
Syntax definition:
The syntax of the httpapplicationstate class is defined as follows:
Public sealed class httpapplicationstate: nameobjectcollecionbase
"Nameobjectcollectionbase" is the base class of the application state, indicating the combination of key/value pairs. All values are of the object type. Because of its inherited interface icollecion, you can use the index method to access these set data.
The use of the httpapplicationstate class is completed by the internal object "application", for example:
Application ["applicationname"] = "school ";
Attribute details:
Because the content stored in httpapplicationstate is a key/value pair, its attributes are similar to those of most key/value pairs, and they all have attributes such as keys, item, and count. These attributes and their descriptions are listed below:
Allkeys: All keys used to access the data set
Contents: Get the content of the data set
Count: obtains the total number of data items in a dataset.
Item: obtains an item in a dataset.
Keys: Get the key set
Detailed solution:
Since you need to store data in httpapplicationstate, you must have a common method for adding, deleting, and other data.
Add: add data to a collection
Clear: clears the data in the set.
Get: Get the data in the set through the index
Getkey: Get data through the key value
Lock: Lock the set to synchronize data updates.
Remove: Remove a variable.
Removeall: removes all variables.
Removeat: removes a variable from the set by index.
Set: set the value of a variable in the set.
Unlock: the contact locks the set.
The following code demonstrates how to use methods in the httpapplicationstate class:
Application. add ("name", "cgj"); // Add a key value response. write (application. get ("name "). tostring (); // The value of the Return key application. add ("Age", "12"); // Add a key value response. write (application. getkey (0 ). tostring (); // returns the name of the first key application. lock (); // lock the application status and keep the application updated and synchronized. set ("name", "chengj"); // modify the value of the key name application. unlock (); // unlock the application. removeat (0); // remove the first key-Value Pair
Typical applications: Use the httpapplicationstate class to save database connection strings
A database connection string is an application-level variable. To ensure that all sessions can be accessed, this example stores them in the httpapplicationstate class. This is not the best solution, because. Net supports storing strings in the configuration file for global calling.
In the application-started event "application_start", write the following code to add the key/value pair of the connection string:
If (application ["connstring"] = NULL)
Application ["connstring"] = "Data sourse = server; initial catalog = MIS; uid = sa; Pwd = ;";
In the Code view on the default. aspx page,
If (application ["connstring"]! = NULL)
Response. Write (application ["connstring"]. tostring ());
Enterprise applications:
/// <Summary> /// put the object into the cache /// </Summary> /// <typeparam name = "T"> wafobject type </typeparam>/ // <Param name = "T"> wafobject object </param> internal static void setuserobject <t> (T) where T: wafobject {If (httpcontext. current! = NULL) {string guid = loginuser. guid; If (httpcontext. current. application [guid] = NULL) httpcontext. current. application. add (guid, new sortedlist <string, wafobject> (); sortedlist <string, wafobject> List = httpcontext. current. application [guid] As sortedlist <string, wafobject>; string key = typeof (t ). fullname; If (list. containskey (key) {list [Key] = T;} else {list. add (Key, T );}}}
Httpcookie type
Cookies are also used to save data, but only for a single user. It also saves a set of key/value pairs. The biggest difference from the httpapplicationstate class is the validity period. The application object does not have any validity period. Only deletion is considered as the expiration time of the object. When the cookie is created, you can specify the expiration time of the key/value pair. Cookies are generally used to save the login user name and password, so that you do not need to fill in the next login. This improves the user's work efficiency, but there are certain security issues.
Syntax definition
Public sealed class httpcookie
Httpcookie constructor has two types: one is not assigning values to keys, and the other is specifying key/value pairs. The function code is as follows:
Public httpcookie (string name)
Public httpcookie (string name, string value)
Attribute details:
The httpcookie class contains some attributes for accessing the internal key/value pair, such as the key value and expiration time.
Expires: Cookie Validity Period
Haskes: determines whether a cookie has a subkey.
Item: access the variables in the cookie set by index
Name: Cookie name
Path: the virtual path transmitted together with the cookie
Secure: whether to use HTTP to transmit cookies
Value: Specifies the cookie value.
Values: cookie value set
Typical application: Use httpcookie to save user login information
The main application of httpcookie is to save some common information of the current login user, which will be stored on the client machine. This example shows how to save the current login name and password.
Request. cookies. clear (); // clear all cookiehttpcookie myname = new httpcookie ("userinfo"); // create an httpcookie instance myname ["name"] = textbox1.text; // Save the variable myname ["pass"] = textbox2.text;/myname. expires = datetime. now. addhours (1); // set the cookie expiration time repsonse. cookies. add (myname); // Add the cookie to the cookie set of the Web request. Note: After the httpcookie is configured, you need to add it to the cookie set of the Web request in the page_load event, obtain the saved cookie. The Code is as follows: if (request. cookies ["userinfo"]! = NULL) {// obtain the user name and password textbox1.text = request. cookies ["userinfo"] ["name"]. tostring (); testbox2.text = request. cookies ["userinfo"] ["pass"]. tostring ();}
URL encoding/decoding: httputility class
The httputility class mainly provides URL encoding and decoding methods. This is for the sake of URL data security, because the encoded data cannot be easily identified. If you want to read URL data, it must be decoded. This also prevents Web client script injection. The httputility class uses all encoding and decoding methods, including string encoding and byte array encoding. This class does not provide any attributes.
Syntax definition
The syntax of the httputility class is defined as follows:
Public sealed class httputility
The "sealed" keyword indicates that this class is a sealed class and cannot be inherited.
Generally, the objects that call the httputility class are not completed by instantiating the class, but by calling the internal "sever" object and using its public methods and attributes, however, the server does not fully support these methods.
The internal methods of the httputility class are mostly static methods, which ensures that these methods can be used without instantiation. As follows:
Httputility. htmlencode ("This is test ");
Detailed description
The httputiity class mainly implements encoding and decoding of characters, URLs, and other data. The specific method is as follows:
Htmldecode: decodes strings.
Htmlencode: String Encoding
Parsequerystring: returns the query string.
Urldecode: decodes the URL transmission string.
Urldecodetobytes: decodes data transmitted from a URL into a byte group.
Urlencode: encode the URL transmission string.
Urlencodetobytes: encode the data transmitted by the URL into a byte group.
Urlencodeunicodetobytes: converts Unicode data to a byte array.
Urlpathencode: encode the transmission path
The following shows how to use the methods in the httputlity class:
Httputiltiy. htmlencode ("this is test ");
Httputility. htmldecode ("this ");
Httputility. urlencode ("the world ");
Httputility. urldecode ("the world ");
Httputility. urlencodeunicode ("the world ");
Namevaluecollection myvalue = httputility. parsequerystring ("name = cgj & age = 28 ");
Typical application: Use a page to pass Chinese Parameters
Passing Chinese characters between pages has always been troublesome, mainly because of two reasons: security and garbled characters. When using JavaScript, you can use the function "escape" to solve this problem. In C #, you can use the httputility class to easily solve the secondary problem. Generally, this mode is used for large websites.
Transfer between pages. default. aspx page:
String strurl = "default2.aspx ";
String name = httputility. urlencode ("Liu Qiqian"); // Encoding
String type = httputility. urlencode ("computer engineer ");
Reponse. Redirect (strurl + "name =" + name + "& type =" + type); // navigation
Open the default2.aspx page and write the code to get the passed parameters in its "page_load" event, as shown below:
Response. Write (request. Query ["name"]); // get the parameter name
Response. Write (request. Query ["type"]); // obtain the type parameter
Press F5 to run the program. You can see that the URL of the page no longer displays the value content, but shows some messy encoding. This ensures the parameter security.
Manage uploaded files: httppostedfile
The httppostedfile class manages a single file uploaded by the client, and the management of all files is handed over to the "httpfilecollection" class. In fact, the httppostedfile class is an individual of the httpfilecollection class.
You can use the httppostedfile class to obtain attributes of the uploaded file, such as the size and file name. You can also use the "saveas" method provided by this class to save files.
Syntax definition:
The syntax of the httppostedfile class is defined as follows:
Public Seald class httppostedfile
In actual applications, you do not need to use new to construct such an instance. Instead, you can use the "postedfile" attribute of the "fileupload" control to obtain the instance. The usage is as follows:
Httppostedfile myfile = fileupload1.postedfile;
Attribute details:
The attributes of the httppostedfile class are used to describe some basic information about the uploaded file.
Contentlength: the length of the uploaded file.
Contenttype: Object MIME type
Filename: file path name
Inputstream: stream for reading files
Detailed solution:
The htttpostedfile class is mainly used to obtain information about the uploaded files. Currently, only one "savaas" method is provided to save the uploaded files to the server.
The syntax for using saveas is as follows:
Public void saveas (string filename)
The parameter "FILENAME" indicates the target path and file name.
The following code demonstrates how to use the saveas method:
Myfile. saveas (@ "C: \ test.doc ");
Typical applications: perform different processing based on the size of the uploaded file.
Httppostedfile myfile = fileupload1.postedfile; // obtain the upload file instance // obtain the file name string filename = myfile. filename. substring (myfile. filename. lastindexof (@ "\") + 1); If (myfile. contentlength> 1024000) // determine the file size, greater than 1 MB myfile. saveas (@ "C: \ bigfile \" + filename); // The folder "bigfile" else myfile must exist under drive C. saveas (@ "C: \ smallfile \" + filename); // The folder "smallfile" response must exist under drive C. write ("saved successfully ");
Application runtime service: httpruntime
The httpruntime class is used to provide ASP. NET runtime services, mainly for the currently running applications. Through the methods and Attributes provided by this class, you can obtain some basic information about the application. The most important thing in the httpruntime class is the method "processrequest", which is used to process all subsequent web operations. By understanding the method, you can understand the running process of the application.
Encapsulate HTTP Request Information: httpcontext
Httpcontext is a very important class in Web applications. The reason why it is put later is that its attributes are instance objects of many classes, "httpresponse", "httprequest", and "tracecontext. The following describes the attributes of httpcontext, which encapsulate the information used by HTTP requests.
The httpcontext class manages all attributes of an HTTP request, including the request input stream, output stream, user of the current request, and cache object. The httpcontext class is the context of Web requests. Each request is accompanied by an httpcontext object, which is used to encapsulate request-related information. To classify such information, the response class, request class, session class, cache class, and trace class are mainly used. When the request ends, the httpcontext object of the request disappears.
Syntax definition
The syntax of the httpcontext class is defined as follows:
Public sealed class httpcontext: iserviceprovider
The "sealed" keyword indicates that this class is closed and cannot be inherited. The httpcontext class implements the interface "iserviceprovider" to retrieve service objects.
When using the httpcontext class, Initialization is usually not required, and its attributes and Members can be directly called. The call syntax of the httpcontext class is as follows:
Httprequest myreq = httpcontext. Current. request;
Attribute details
The httpcontext class describes all the attributes in the current request. These attributes and their descriptions are listed below.
Allerrors: All Errors in HTTP requests
Application: The Application Object of the current HTTP Request
Applicationinstance: sets the application object for the current HTTP
Cache: current HTTP cache object
Current: The current HTTP httpcontext object
Error: The first error of the current request.
Iscustomerrorenabled: whether to enable custom errors
Isdebuggingenabled: whether it is in debugging mode
Items: Set of HTTP request items
Profile: the configuration file of the current user.
Request: httprequest object of the current request
Reponse: httpreponse object of the current request
Server: the encoding object used to process the request
Session: the session object of the current request.
Skipauthoriaztion: whether to skip the authorization check
Timestamp: the initial timestamp of the current request.
Trace: The tracecontext object of the current response.
User: sets the current user information.
Detailed description
The httpcontext class mainly obtains configuration information. The most important method is "rewritepath", which is used to redirect URLs.
The following describes common methods of the httpcontext class.:
Adderror: add the error message to the error set.
Clearerror: Clear the error message
Getappconfig: Get the configuration information of the current application.
Getconfig: Get the configuration information of the current request
Getglobalresourseobject: obtains application-level resources.
Getlocalresourseobject: Get Page-level resources.
Getsection: Get configuration section information
Rewritepath: rewrite path.
HTTP handler: ihttphandler Interface
The ihttphandler interface mainly uses the custom HTTP handler. For example, when a user accesses a page, the programmer can re-process whether to let the user see the page by implementing the "processrequest" method of this interface.
Custom processing programs can be written in any language that complies with CLS specifications. After a custom processing program is compiled, your requests are not responded to through ASP. NET pages, but through the "processrequest" method implemented by the ihttphanlder interface.
Ihttphandler is widely used, such as popular blog logout technology and access technology with special extensions. These technologies implement the ihttphandler interface to achieve the page processing function.
Syntax definition:
Ihttphandler is an interface defined as follows
Public interface ihttphandler
Interfaces are generally used to encapsulate some fixed operation methods, but do not implement these methods. Therefore, classes that inherit this interface must implement the methods defined in the interface. The ihttphandler interface defines the following content, including an attribute and a method.
# Region ihttphandler Member
Bool ihttphandler. isreusable
{
Get {Throw new exception ("the mothod or operation is not implemented .");}
}
Void ihttphandler. processrequest (httpcontext context)
{
Throw new exception ("the method or operation is not implemented ");
}
# Endregion
Detailed solution:
The ihttphnndler interface has only one method "processrequest", which is mainly used to process Web requests. Its syntax is defined as follows:
Void processrequest (httpcontext context)
The "context" parameter of the method is the context of the current HTTP request, including cache, current request, and response.
The processrequest method is the key to the ihttphandler interface. The page class that is often seen on the Web inherits the ihttphanlder interface and implements its own processrequest method. By understanding this interface, you can also better understand the running principles of webpage pages.
Typical application: Use ihttphandler to deregister a blog
The so-called blog logout technology is that when a user clicks the "logout" button, the page url displays the logout interface, but this logout page does not actually exist, this is the use of ihttphandler interface technology.
Double-click the "logout" button to switch to the Code view of its click event, which is written as follows:
Response. Redirect ("sigeout. aspx"); note: the page "sigeout. aspx" does not exist on the website.
Add a class "sigeouthandler" under the root directory of the website. The system will ask if the class is saved in the "app_code" directory and select "yes ".
The code for designing the "sigeouthandler" class is as follows, and the method "processrequest" in the "ihttphandler" interface is implemented ".
Using system; using system. web; using system. web. security; public class sigeouthandler: ihttphandler {public sigeouthandler () {} bool ihttphandler. isreusable // use context cache {get {return true ;}} void ihttphandler. processrequest (httpcontext context) {formsauthentication. signout (); // Delete the verification ticket httpcontext. current. response. write ("You have successfully logged out"); // display successful information }}
Add the User-Defined processing configuration under the "system. Web" node in the web. config file, as shown below:
<Httphandler>
<Add verb = "*" Path = "sigeout. aspx" type = "sigeouthandler"/>
</Httphandler>
Note: This example uses the login user control. You must set the login mode to "forms" in Web. config ".
Register a user to log on and click "logout". The page URL displayed on the webpage is "http: // localhost/httphandlesample/sigeout. aspx ", but this page does not actually exist. All processing is implemented in the" processrequest "method.
HTTP processing module: ihttpmodule Interface