1. Basic principle Diagram
The IsReusable property is used to indicate whether the handler can be stored in the pool for reuse when the IHttpHandlerFactory object is created IHttpHandler.
Generic Handler (HttpHandler): is a special class that implements the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface is a precondition for the target program as an external request. (Any class that does not implement this interface cannot be requested by the browser.) )
It is called and started by a server that supports ASP. A HttpHandler program is responsible for processing access requests for one or a set of URL addresses that it corresponds to, and receiving access request information (Request messages) from the client and generating response content (response messages).
Simply put: We can generate the browser code by creating our own HttpHandler program to send back to the client browser.
The HttpHandler program can accomplish most of the tasks that ordinary class programs can accomplish:
1. Get the data and URL parameters submitted by the client via HTML form form
2. Create a response message content to the client
3. Accessing the server-side file system
4. Connect to the database and develop database-based applications
5. Calling other classes
2. Life cycle:
19 events for a request pipeline:
(1) BeginRequest: Start processing requests
(2) AuthenticateRequest Authorization authentication request, obtaining user authorization information
(3):P Ostauthenticaterequest for success
(4): Aunthorizerequest authorization, general to check whether the user is granted permission
(5):P ostauthorizerequest: Get authorization
(6): Resolverequestcache: Get page Cache results
(7):P Ostresolverequestcache has obtained cache current request mapping to Mvchandler (PR): Create controller factory, create controller, invoke action execution,
View→response
(8):P Ostmaprequesthandler Create a Page object: Creates a Handler instance that ultimately handles the current HTTP request: First gets the current PR Handler from HttpContext
, Create
(9):P Ostacquirerequeststate get session
(10) Postacquirerequeststate Get session
(11) PreRequestHandlerExecute: Preparing the Page object for execution
ProcessRequest method for executing page objects
(12) PostRequestHandlerExecute finished executing the Page object
(13) ReleaseRequestState Release Request Status
(14) Postreleaserequeststate The request status has been released
(15) Updaterequestcache Update Cache
(16) Postupdaterequestcache Cache has been updated
(17) Logrequest Log Records
(18) Postlogrequest completed Log
(19) EndRequest completed,
3. A small example-the verification of the user name is implemented in the foreground
Before you say a generic handler, look at what ASPX is. In VS, most of the ASPX pages are used. ASPX page is
After a request is received, an HTML page is returned to the server to generate the returned results. When we sometimes need to deal with this result ourselves, instead of returning the HTML directly. How do you do it? This is the time to have a general procedure. A generic handler is a file that has only a CS page and no foreground. The extension is ashx.
Instance Authentication User Name
Js<script type= "Text/javascript" >//verify that the user name is correct function judgeusername () {var username = $ ("#userName"). Val () $. Ajax ({type: "Post", url: ' registerusernameverity.ashx/processrequest?username= ' +username,success:function (Result) {if (username = = "") {alert ("Username cannot be empty! ");d Ocument.getelementbyid (" UserName "). Focus ();d Ocument.getelementbyid (" UserName "). Selected;} else {if (result = = "True") {alert ("already exists, please re-select a user name!") ") document.getElementById (" UserName "). Focus;document.getelementbyid (" UserName "). Select ();}},}); </script>
Html
<input type= "text" onblur= "Judgeusername ()"/>
General processing procedures
1PublicvoidProcessRequest (HttpContext context)2 {3 //get it from the front desk.4String userName = context. Server.urldecode (context. request.querystring["username"]);5 //declares an object that queries whether a user name exists6USERBLL VERIFYUSERNAMEBLL =NewUSERBLL ();7 //to judge by other functions .8BOOL Flag=VERIFYUSERNAMEBLL. Exists (userName);9 if(flag==true)Ten { OneContext. Response.Write (true); A } - Else - { theContext. Response.Write (false); - } -}General processing Procedures
Summarize
This is the front desk directly can not be refreshed to the user name verification, a simple small demon. The key to the general handler is how to get the values that are needed in the foreground into the background. In this way, as long as the general processing procedures to get the value of the foreground, then the operation is much easier to do. The values here are directly inside the link.
Sum up on three points:
1. Pass the value, call the general handler
2. Processing, return the results to the foreground
3. The foreground handles the returned results
4. General handler Ashx method of calling session
How do I get session values on the ASHX page?
Please note the following understandriginally sections:
==========================
On the General Transaction page, you can easily get the Request,response object, thus doing the corresponding operation, as follows:
HttpRequest Request = context. Request;
HttpResponse Response = context. Response;
But it's not that easy to get the value of the session. For example, you want to be in ashx to get the login account that is saved in session session["UserAccount"
If you're just a context. session["UserAccount"] is an exception that will report "object reference not set to an instance of an object"
So, if you want to take a value from the session, you need the following
1. Introduction of namespaces:
Using System.Web.SessionState;
2, the implementation of IRequiresSessionState interface, the specific following
<summary>
Summary description of $codebehindclassname $
</summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
public class Adduserinfo:ihttphandler,irequiressessionstate//This is the implementation of the display, do not implement any method
{
public void ProcessRequest (HttpContext context)
{
//...
So you can do the following.
if (context. session["UserAccount"]! = NULL)
{
String account = Context. session["UserAccount"]. ToString ();
}
//... Continue with the following code
}
}
5. In-depth interpretation of the general process of operating procedures
How does the server receive and send data?
In a generic handler, the ProcessRequest method parameters HttpContext the context call
System Object Action
The way the page points to itself. The scope is the page execution period.
HttpRequest read the value sent by the client during a Web request (HTTP request packet data)
HttpResponse encapsulates the output of the page execution period back to the HTTP client (HTTP response packet data)
HttpApplication State objects acting on the entire program's run time
Session state hold object, used to track a single user's session.
A way for a Cookie client to keep session information
Server provides access to methods and properties on the server
Request (HttpRequest) & Response (HttpResponse)
First, how does the browser submit data? (example) get/post
1. Form: (data hidden in request style, format: txtname=james&txtpwd=123) <form action= "Login.ashx" method= "POST" > <input type= " Text "name=" txtname "/> <input type=" password "name=" Txtpwd "/> </form>
2. URL parameter of the address bar, url,js the URL specified by the hyperlink (same as the form's get mode): Key-value pair http://127.0.0.1/login.ashx?txtname1=jordan&txtpwd1=123
Second, how does the server get the data submitted by the browser?
1. Get Post data: context.request.form["Txtname"]
2. Get the Get parameter: context.request.querystring["Txtname1"]
Third, how does the server output data to the browser?
Context. Response.Write ("I am the data from the server output to the browser!") :)”);
Request (HttpRequest) Common members
How do you pass data between pages? (get/post: Hyperlink, Location,js submit (), form submit button)
Getting Started 1.html
<form action= "Getting Started 1.ashx" > <input type= "text" name= "username"/><input type= "submit"/> </form>
Create a new generic handler get started 1.ashx, write in ProcessRequest
Context. Response.ContentType = "text/html";
String username = context. request["username"];
Context. Response.Write (username + "<font color= ' red ' > Hello </font>" +guid.newguid ());//based on the current computer's hardware number + system time microseconds
Whenever a user requests access to the ASHX page, the ProcessRequest method is called, where it accesses the context. Request to get visitor parameters such as requests. It then sends the data back to the browser via Context.response to the browser in ProcessRequest. At the end of the ProcessRequest, the server is the user of this access service.
The browser submits data to the server side, the form of the submitted data (input, select, textarea, and so on) into the form, which is set by the Action property in the form, in order to fetch the value of the table item on the service side, You need to set the Name property for the form element in HTML, note that the ID is for the JS Operation Dom, and name is for the server. Use the context on the server side. request["username"] to get the submitted property value based on the name of the form item. Through the context. Response.Write Displays HTML content after processing to the browser.
When we click on the "Submit" button, the browser will "extract" the values in the controls such as the user's text box and send it to the server instead of the server to read the page that the user filled out. Which tags will be submitted to the server? The following conditions apply to the submission of user-filled content to the server:
Only input, textarea, select three types of labels can be used. Only input (text box, checkbox, etc.) users may fill in the values,<label>, <p>, <font> and other labels for display purposes only, no need to submit to the server.
Only the value of the Value property is submitted to the server. As an example of the input tag, the input tag has a title, type, disabled, and so on, but these properties are for display purposes, and the user cannot modify it, only the Value property is the user-entered property, so only values of the Value property are committed to the server.
The label must set the Name property. When we learn the DOM, we know that if you want to manipulate the tag through JavaScript, you must set the ID for the tag. If you want to commit the Value property of the label to the server, you must set the Name property for the label, and submit it to the server with a "Name=value" key-value pair to the server, with & split between multiple key-value pairs. In addition to a few labels, such as radio buttons, the value of the name of most labels cannot be duplicated. The name is for the server, and the ID is for the DOM. For RadioButton, the same name as a group, the selected RadioButton value is submitted to the server.
If the disabled property of the control is set, the browser does not commit the value of the control.
Put it in the Form tab. Only tags placed inside the form tag may be submitted to the server, and tags such as input outside the form are ignored.
". NET project: ". NET generic Handler usage methods