|
|
|
|
|
|
Author Rank:
|
|
Technologies:
.NET 3.0 and 3.5, ASP.NET 3.5,Visual C# .NET
|
|
Total downloads :
|
156
|
|
Total page views :
|
12005
|
|
Rating :
|
|
3.67/5
|
|
This article has been rated :
|
3 times
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
Related EbooksTop Videos
|
|
|
Description
|
|
The Complete Visual C# Programmer's Guide, written by the authors of C# Corner, covers most of the major components that make up C# and the .NETenvironment including Windows Forms, ADO.NET, GDI+, Web Services, and Security. The book is geared toward the beginner to intermediate programmers.
|
|
|
|
|
|
|
|
|
|
|
|
|
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 types of interception HttpModule and HttpHandler. This article walks through it.
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 code behind 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 HttpHandlers and HttpModules.

HttpHandler - The Extension Based Preprocessor
HttpHandler help us to inject pre-processing logic based on the extension of the file name requested. So when a page is requested, HttpHandler executes 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", handler3 pre-processing logic executes.

HttpModule - The Event Based Preprocessor
HttpModule is 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 requests.

Steps to Implement HttpHandlers
Step 1
HttpHandlers are nothing but classes which have pre-processing logic implemented. So the first thing is to create a class project and reference System.Web namespace and implement the IHttpHandler interface as shown in the below code snippet. IHttpHandler interface has two methods which needs to be implemented; one is the ProcessRequest and the other is the IsResuable. In the ProcessRequest method, 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.
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 just need to make an entry of HttpHandlers tag. In the tag, we need to specify which kind of extension requested will invoke our class.
<system.web> <httpHandlers> <add verb="*" path="*.Shiv,*.Koirala" type="MyPipeLine.clsMyHandler, MyPipeLine"/> </httpHandlers> </system.web>
Once done, request for page name with extension a shiva and you should see a display as shown below. So what has happened is when the IIS sees that request is for a a.shiva page extension, it just calls the clsMyHandler class pre-processing logic.
 Steps to Implement HttpModule
Step 1
As discussed previously, HttpModule is an event pre-processor. So the first thing is to implement the IHttpModule and register the necessary events which this module should subscribe. For instance, we have registered in this sample for BeginRequest and EndRequest events. In those events, we have just written an entry onto the log file.
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 the HttpModule tag as shown in the below code snippet:
<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.
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
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other
Visual Studio release. Work more productively and collaboratively-with
greater control over your work at every step. The Beta 2 can give you a
head start on achieving efficiency.
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|