The Two Interceptors: HttpModule and HttpHandlers
2012-08-06 22:35
471 查看
http://www.codeproject.com/Articles/30907/The-Two-Interceptors-HttpModule-and-HttpHandlers
Table of Contents
IntroductionThe Problem
HttpHandler - The Extension Based Preprocessor
HttpModule- The Event Based Preprocessor
The Overall Picture of Handler and Modules
Steps to Implement HttpHandlers
Steps to Implement HttpModule
The Final Output
Reference
Introduction
Many times we want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two typesof interception
HttpModuleand
HttpHandler. This article walks through
it.
For the last few days, I have been writing and recording videos in design patterns, UML, FPA, Enterprise blocks and lot more. You can watch the videos here.
You can download my 400 .NET FAQ EBook from here.
The Problem
Many times we need to inject some kind of logic before the page is requested. Some of the commonly used pre-processing logics are stat counters, URL rewriting, authentication / authorization and many more. We can do this in the codebehind but then that can lead to lot of complication and tangled code. The code behind will not solve the purpose because in some implementations like authorization, we want the logic to execute before it reaches the resource. ASP.NET provides two ways of
injecting logic in the request pipeline
HttpHandlersand
HttpModules.
HttpHandler - The Extension Based Preprocessor
HttpHandlerhelp us to inject pre-processing logic based on the extension of the file name requested. So when a page is requested,
HttpHandlerexecutes
on the base of extension file names and on the base of verbs. For instance, you can visualize from the figure below how we have different handlers mapped to file extension. We can also map one handler to multiple file extensions. For instance, when any client
requests for file with extension ‘GIF’ and ‘JPEG’,
handler3pre-processing logic executes.
HttpModule- The Event Based Preprocessor
HttpModuleis an event based methodology to inject pre-processing logic before any resource is requested. When any client sends a request
for a resource, the request pipeline emits a lot of events as shown in the figure below:
Below is a detailed explanation of the events. We have just pasted this from here.
BeginRequest: Request has been started. If you need to do something at the beginning of a request (for example, display advertisement
banners at the top of each page), synchronize this event.
AuthenticateRequest: If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate
the password), build a module that synchronizes this event and authenticates the user in a way that you want to.
AuthorizeRequest: This event is used internally to implement authorization mechanisms (for example, to store your access control lists
(ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.
EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then
writes the information to the page.
We can register these events with the
HttpModules. So when the request pipe line executes depending on the event registered, the logic
from the modules is processed.
The Overall Picture of Handler and Modules
Now that we have gone through the basics, let's understand what is the Microsoft definition for handler and modules to get the overall picture.Reference: INFO: ASP.NET HTTP Modules and HTTP Handlers Overview
“Modules are called before and after the handler executes. Modules enable developers to intercept, participate in, or modify each individual request. Handlers are used to process individual endpoint requests. Handlers enable the ASP.NET
Framework to process individual HTTP URLs or groups of URL extensions within an application. Unlike modules, only one handler is used to process a request”.
Steps to Implement HttpHandlers
Step 1
HttpHandlersare nothing but classes which have pre-processing logic implemented. So the first thing is to create a class project and reference
System.Webnamespace
and implement the
IHttpHandlerinterface as shown in the below code snippet.
IHttpHandlerinterface
has two methods which needs to be implemented; one is the
ProcessRequestand the other is the
IsResuable.
In the
ProcessRequestmethod, we are just entering the URL into the file and displaying the same into the browser. We have manipulated the context response object
to send the display to the browser.
Collapse | Copy
Code
using System; using System.Web; using System.IO; namespace MyPipeLine { public class clsMyHandler : IHttpHandler { public void ProcessRequest(System.Web.HttpContext context) { context.Response.Write("The page request is " + context.Request.RawUrl.ToString()); StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true); sw.WriteLine("Page requested at " + DateTime.Now.ToString() + context.Request.RawUrl); sw.Close(); } public bool IsReusable { get { return true; } } }
Step 2
In step 2, we need to make an entry ofHttpHandlerstag. In the tag, we need to specify which kind of extension requested will invoke our
class.
Collapse | Copy
Code
<system.web> <httpHandlers> <add verb="*" path="*.Shiv,*.Koirala" type="MyPipeLine.clsMyHandler, MyPipeLine"/> </httpHandlers> </system.web>
Once done, request for page name with extension ‘Shiv’ and you should see a display as shown below. So what has happened is when the IIS sees that request is for a ‘.shiv’ page extension, it just calls the
clsMyHandlerclass
pre-processing logic.
Steps to Implement HttpModule
Step 1
As discussed previously,HttpModuleis an event pre-processor. So the first thing is to implement the
IHttpModuleand
register the necessary events which this module should subscribe. For instance, we have registered in this sample for
BeginRequestand
EndRequestevents.
In those events, we have just written an entry on to the log file.
Collapse | Copy
Code
public class clsMyModule : IHttpModule { public clsMyModule() {} public void Init(HttpApplication objApplication) { // Register event handler of the pipe line objApplication.BeginRequest += new EventHandler(this.context_BeginRequest); objApplication.EndRequest += new EventHandler(this.context_EndRequest); } public void Dispose() { } public void context_EndRequest(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true); sw.WriteLine("End Request called at " + DateTime.Now.ToString()); sw.Close(); } public void context_BeginRequest(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true); sw.WriteLine("Begin request called at " + DateTime.Now.ToString()); sw.Close(); } }
Step 2
We need to enter those module entries into theHttpModuletag as shown in the below code snippet:
Collapse | Copy
Code
<httpModules> <add name="clsMyModule" type="MyPipeLine.clsMyModule, MyPipeLine"/> </httpModules>
The Final Output
If you run the code, you should see something like this in the RequestLog.txt. The above example is not so practical. But it will help us understand the fundamentals.Collapse | Copy
Code
Begin request called at 11/12/2008 6:32:00 PM End Request called at 11/12/2008 6:32:00 PM Begin request called at 11/12/2008 6:32:03 PM End Request called at 11/12/2008 6:32:03 PM Begin request called at 11/12/2008 6:32:06 PM End Request called at 11/12/2008 6:32:06 PM Begin request called at 11/12/2008 8:36:04 PM End Request called at 11/12/2008 8:36:04 PM Begin request called at 11/12/2008 8:37:06 PM End Request called at 11/12/2008 8:37:06 PM Begin request called at 11/12/2008 8:37:09 PM End Request called at 11/12/2008 8:37:09 PM Begin request called at 11/12/2008 8:37:38 PM Page requested at 11/12/2008 8:37:38 PM/WebSiteHandlerDemo/Articles.shiv End Request called at 11/12/2008 8:37:38 PM
Reference
INFO: ASP.NET HTTP Modules and HTTP Handlers Overview
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
Shivprasad koirala
相关文章推荐
- The Two Interceptors: HttpModule and HttpHandlers
- Apache错误:LoadModule takes two arguments, a module name and the name of a shared object
- ./configure: error: the HTTP rewrite module requires the PCRE library
- IIS 7 与 IIS 6 中在HttpModule和HttpHandlers中的区别
- 【12】Adds two numbers represented by a linked list and returns the sum as a linked list
- Configuring and Customizing the Content Query Web Part(转http://blogs.msdn.com/b/ecm/archive/2006/10/
- Edge.js:让.NET和Node.js代码比翼齐飞(http://www.infoq.com/cn/articles/the_edge_of_net_and_node)
- CentOS安装Nginx 报错“configure: error: the HTTP rewrite module requires the PCRE library”解决办法
- Send an image from the iPhone using ASIHTTP and UIImagePicker
- Compare Two object and put the result into xmlFile
- greecket - a python not block socket module base the greenlet and thread - Google Project Hosting
- CXF报错[1 counts of IllegalAnnotationExceptions]and[Two classes have the same XML type name]and[Use @XmlType.name and @XmlType.namespace to assign different names to them]
- You can either disable the module by using --without-http-cache option, or install the OpenSSL libra
- Ngnix安装error: the HTTP rewrite module requires the PCRE library.
- [CrackCode] 2.4 Add two numbers and return the sum as a linked list
- Find the difference between two days in days, months and years
- linux下安装nginx error: the HTTP rewrite module requires the PCRE library.
- Custom Authentication provider by implementing IHttpModule, IPrincipal and IIdentity
- HttpModule 和 HttpHandlers(转)
- 170.Which two statements are true regarding the DELETE and TRUNCATE commands? (Choose two.)