Reproduced:
Overview
From the previous chapters we know that HTTP handler provides functionality similar to the ISAPI Server extention, and HttpModule implements functionality similar to ISAPI filter. Using a custom handler overrides the default handler of the system, and module can exist multiple simultaneous.
HttpHandler and HttpModule are simply the processing of a request context, but their two functional roles are completely different. I still can't think of a simple and can embody the httphandler of the advantages of the scene, in fact, the page class is a implementation of the IHttpHandler class, Ajax also has relevant implementation, as well as asp.net forums There are two simpler implementations (Avatarhttphandler and Vcardhttphandler) in V2, and you can refer to them.
The following is an example of a httpmodule check whether a user is logged in and the module is licensed.
Scene
A website that has a homepage (default.aspx), a login page (login.aspx), two modules (Module 1 and Module 2).
First, when the user is not logged in the case of access to any page of the site will jump to the login page to require users to log in, after the completion of the site to jump to the homepage and on each page to display the Welcome word.
Second, false with two users, a "STWYHM", a "1,stwyhm", the field can access the Module 2, when they access to the modules they have access to, the display module gives the welcome word, if the Access module does not have access rights, give error prompts. Other users can only access pages after the specified module.
Sample
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Web;
Namespace Authorizationmodule
{
<summary>
Description: Check the user Login module
Author: Wen Ye
Contact: stwyhm.cnblogs.com
</summary>
public class Userauthorizationmodule:ihttpmodule
{
#region IHttpModule Members
public void Dispose ()
{ }
public void Init (HttpApplication context)
{
Context. AcquireRequestState + = new EventHandler (context_acquirerequeststate);
}
void Context_acquirerequeststate (object sender, EventArgs e)
{
Get application
HttpApplication application = (HttpApplication) sender;
Check if the user is logged in
if (application. context.session["UserName"] = = NULL | | Application. context.session["UserName"]. ToString (). Trim () = = "")
{
Get URL
String requesturl = Application. Request.Url.ToString ();
String requestpage = requesturl.substring (Requesturl.lastindexof ('/') + 1);
If the requested page is not a login page, it is just redirected to the login page.
if (requestpage!= "Login.aspx")
Application. Server.Transfer ("Login.aspx");
}
Else
{
Logged in to print a welcome word to each requested page.
Application. Response.Write (String. Format (welcome.) {0}. ", Application. context.session["UserName"]);
}
}
#endregion
}
<summary>
Description: Checks whether the user has permission to use module
Author: Wen Ye
Contact: stwyhm.cnblogs.com
</summary>
public class Systemmoduleauthorizationmodule:ihttpmodule
{
#region IHttpModule Members
public void Dispose ()
{
}
public void Init (HttpApplication context)
{
Context. AcquireRequestState + = new EventHandler (context_acquirerequeststate);
}
void Context_acquirerequeststate (object sender, EventArgs e)
{
HttpApplication application = (HttpApplication) sender;
If the user is not logged on, the module authorization does not need to be checked because the request is redirected to the login page by the user login module.
if (application. session["UserName"] = = null)
Return
Get user name and URL
String userName = Application. session["UserName"]. ToString ();
String url = Application. Request.Url.ToString ();
If the user is not authorized, the request is terminated and a message is printed.
if (! Validator.canusemodule (userName, URL))
{
Application.completerequest ();
Application. Response.Write (String. Format ("Sorry.") {0}, you do not have permission to access this module. ", UserName));
}
}
#endregion
}
public class Validator
{
<summary>
Check whether the user is authorized to use the module.
STWYHM can use modules, and all users can request a page that is outside the module.
</summary>
<param name= "UserName" ></param>
<param name= "url" ></param>
<returns></returns>
public static bool Canusemodule (string userName, string url)
{
if (!url. Contains ("module"))
return true;
else if (userName = = "Wen ye" && url. Contains ("Module 1"))
return true;
else if (UserName = = "stwyhm" && URL. Contains ("Module 2"))
return true;
Else
return false;
}
}
}
There is no code in the page except for a simple login to save the user name to session code and some HTML rendering code.
Execution Results
The first step: Open the homepage of the website, the login is jumped to the login page
Step two: After the login succeeds, jump to the first side.
Step three: Access to modules 1
Step Fourth: Access to Modules 2
Development Attention Points
Whether it's a request through a URL or a page postback caused by a button, it's the same for IIS, and it's a request. Events in HttpModule are generally in front of page events, especially control events, so if you filter the request in a HttpModule event, you do not perform a page event or control event. This is why the Userauthorizationmodule code in the above example makes a decision about whether the request page is login.aspx.
Summary
Here two custom HttpModule implement the function of the filtering request that they want to achieve, one restricts the user to login, a restricted module accesses, of course the actual application is much more complicated than this. Such authentication method is simple, safe, the code changes as long as the corresponding HttpModule can be modified, do not have to write the same validation code on each page, and will not occur in the URL of the address bar to enter a URL can be skipped login and other verification of the situation. In these two HttpModule, because all have to involve to the session's visit, all uses the AcquireRequestState event, everybody may use the different event according to the actual situation, may refer to the HttpModule life cycle diagram in my previous article.