ASP.NET HTTP Modules:
HTTP Modules:
HTTP Modules use to intercept HTTP requests for modifying or utilize HTTP based requests according to needs like authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching....
HTTP Modules are activated/called/invoked before and after HTTP Handler execution.
HTTP Modules are integral part of ASP.NET framework now and heavily being used as it cater grips upon request and let developers to generate response in a customized way, according to user requirement. Web development is all about playing with request from client to server and response from server to client.
When any request goes to web server, request passes through different phases and then at last response gets generate for client.
HTTP Modules are .Net based components/Plugins and programmed by implementing System.Web.IHTTPModule interface of .Net.
HTTP Module Background:
Before HTTP Modules, web developers/programmers used to implement Internet Server Application Programming Interface (ISAPI) Filters like me (wish interviewer asked me about by terms of ISAPI at that time then I tell him ( )), anyhow jokes apart.
As name implies ISAPI is a web server based API and used to manage request which comes to web server and generate response. ISAPI based upon web server (IIS) where as NSAPI is Netscape based web server API.
ISAPI is based upon win32 DLL and programmed in unmanaged code C/C++, which is somehow painful (:$) and due to unmanaged code, is less reliable, scalable and quite complex to implement than HTTP Modules by managed code under the framework of .Net. Hope you got it why ISAPI Filters replaced by HTTP Modules (;))
Asp.net requests goes through HTTP Modules events just like (oil flowing through pipeline and that pipeline has some filters to refine that oil)
HTTP Modules Events:
Every HTTP Module must implement following two methods of IHTTPModule interface:
Init: To register/initialize event handler to the events of HTTP Module for HTTP based application.
Dispose: To perform a clean up code means resource releasing, object removing from memory and such other resources releasing which used explicitly.
Following are list of events with their brief description:
BeginRequest: Event fired whenever any asp.net based request sent to web server. If you need to do perform at the beginning of a request for example, modify show banners, log HTTP Header information, Get/Set cultures, Response.Filter to generate response for browser according to your need.
AuthenticateRequest: If you want to check authentication of request that request comes from authenticated user or not means wants to implement custom authentication scheme. For example, look up a requested user credentials against a database to validate.
AuthorizeRequest: This method is used specifically to implement authorization mechanisms means authenticated user/request has what privileges/rights/access in that specific application for example, either user has access on all pages or not of that website or has write to create file or not or visit report pages and like this.
ResolveRequestCache: This event determines if a page served from the Output cache. If you want to write your own caching module (for example, build a file-based cache rather than a memory cache), synchronize this event to determine whether to serve the page from the cache.
AcquireRequestState: Session state is retrieved from the state store. If you want to build your own state management module, synchronize this event to grab the Session state from your state store.
PreRequestHandlerExecute: This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute: This event occurs after the HTTP handler is executed.
ReleaseRequestState: Session state is stored back in the state store. If you are building a custom session state module, you must store your state back in your state store.
UpdateRequestCache: This event writes from output back to the Output cache. If you are building a custom cache module, you have to write the output back to your cache.
Error: this event always occurs when any exception (unhandled error occurs in application, this event specifically uses to handle or log error messages of that web application. (Heavily used in Error Logging Modules and Handlers (ELMAH) kind of applications). You can learn about ELMAH more from following link in detail:http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx
EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information on the page.
By above events list you must be getting wonder about difference between Global.asax as somehow events of Global.asax are pretty same, so let me tell you difference between Global.asax and HTTP Module (another common question asked in interviews)
But you need to register/initialize these Events explicitly in “Init” method; following is sample code of IHTTPModule implementation for couple of events.
Hide Shrink Copy Code
"kwd">using System; "kwd">using System.Web; "kwd">using System.Collections; "kwd">public class HelloWorldModule : IHttpModule { "kwd">public String ModuleName { "kwd">get { "kwd">return "st">"HelloWorldModule"; } } "cmt">// In the Init function, register for HttpApplication // events by adding your handlers. "kwd">public void Init(HttpApplication application) { application.BeginRequest += ("kwd">new EventHandler("kwd">this.Application_BeginRequest)); application.EndRequest += ("kwd">new EventHandler("kwd">this.Application_EndRequest)); } "cmt">// Your BeginRequest event handler. "kwd">private void Application_BeginRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("st">"<h1><font color=red>HelloWorldModule: Beginning of Request</font></h1><hr>"); } "cmt">// Your EndRequest event handler. "kwd">private void Application_EndRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("st">"<hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>"); } "kwd">public void Dispose() { } }
Ref: msdn
HTTP Module vs Global.asax
2. According to life cycle of Request, Request passed through HTTP Module first and then through Global.asax
3. Following are list of events which are supported in Global.asax but unfortunately not in HTTP Module.
- Application_OnStart
This event is raised when the very first request passed through the web application. - Application_OnEnd
This event is raised just before the application is going to terminate. - Session_OnStart
This event is raised for the very first request of the user's session. - Session_OnEnd
This event is raised when the session is abandoned or expired.
Here I would like to share one more interview experience of me but now its about my friend’s interview, for which he did preparation from me/took my help or guidance for it Anyhow whilst I was helping him in his preparation for asp.net technical interview, I asked him: “ tell me when session starts?” He replied: “Simple when user logins from login page”, I said ok! Suppose site has no login page and could be accessible by anonymous user, session will never start and Session_OnStart event of Global.asax will never fire then is it? He replied: of course, I couldn’t stop me to smile; I might not laugh if he has no experience or less experience but he has more than 4 years of experience. Anyhow next day when he went for interview, interviewer asked him the same question and he smiled and said, “If you think I will say when user login session_Onstart event will fire then you are wrong. (They also started laughing).
Anyhow normally people say or according to books to tell reader in easy way that session are user based, NO! Sessions are actually browser based. Anyhow shouldn’t go away from topic as much.
Registering HTTP Module
The following is an example of registering/adding an HTTP module:
<httpModules> <add type="ClassName, AssemblyName" name="ModuleName" /> <httpModules>
Following is the list of module is defined at machine.config or web.config by default. ($WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG\ CONFIG Files)
Performance:
You can improve performance of your application by removing default (but not in used) HTTP Modules registered in machine.config file as these are activated/invoked/called on each request for your application unnecessarily by <remove …> for example,
But please make sure before its implementation/applying that you are not using them. If you are using any of these, you may exclude that from existing list.
Conclusion
HTTP Modules are quite simple to understand and quite flexible by means of its number of events. HTTP modules integrate with whole application and every request passed through HTTP Module. So HTTP Module should be implemented very carefully. Take the time to completely understand its advantages, disadvantages, implementation and concepts before implementing a solution.
To get more detailed understanding of HTTP Modules with real time examples implmentation, I would recommend you to visit following links:
For URL Redirection example click here
For Security based example click here
For IP based security example click here
For Error Manager Example click here
No comments:
Post a Comment