When to use HttpHandlers and HttpModules? - asp.net

When exactly to use HttpHandlers and HttpModules?
Can't I write that code in ASPX pages' code behind?

HttpModule allows you to intercept the request (before it is handled by its handler) and response generated. It can modify both request/response if needed. ASP.NET sessions, profiles, authentication etc is also implemented as HttpModule - these module inspects the request and attach necessary context (e.g. session state based on session cookie) to the request. Such functionality is difficult to achieve via aspx code behind.
HttpHandler is the one responsible for handling the request i.e. to generate HTTP response which often (but not always) means generating some html. The page class (base for aspx) is nothing but http handler (so are other end points such as asmx, ashx, axd). The raw handler (ashx) is useful when you need absolute control over response generation - it would be possible to use aspx instead but then it would unnecessarily involve all default page/control machinery (view-state, post-date, control tree etc).

Related

Process Request method in Page Life Cycle

I need to understand the below statements
Statement - 1
The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
Statement - 2
You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)
Statement - 3
What is the importance of ProcessRequest in Page Life Cycle?
Definitions
HTTP - A protocol that allows clients and servers to talk with each other.
IIS - A Microsoft "web server". By "web server" I mean an application that does three things: listens for incoming HTTP Requests, handles them, and then replies with an HTTP response.
ASP.NET - A framework built on top of .NET used to create custom logic for HTTP requests.
ASP.NET Web Application - A type of Visual Studio project. These projects work, primarily, by integrating with a web server (e.g. IIS). Building doesn't create an executable of any kind.
IIS Pipeline - The series of events an HTTP request goes through once it enters IIS.
HTTP Handler - The primary logic for determining the HTTP Response to an HTTP Request. Only one HTTP handler is used per request. The handler is typically chosen by the extension of the requested resource. For example, if a .jpg, .png, or .gif (i.e. an image) is requested the handler could simply return the image. If a .php page were requested the handler could return the results of executing the PHP file. IIS comes with its own native handlers. ASP.NET adds to these and also allows you to write your own custom handlers.(as an example a list of handlers on an IIS website)
IIS and ASP.NET Web Applications
There is a complicated relationship between IIS and ASP.NET (from here forward ASP.NET will mean a web application unless otherwise noted). It can be difficult to tell where one begins and the other ends.
Perhaps the most important distinction between the two is that while IIS is a stand-alone application, ASP.NET relies on a server, like IIS, to run. This means there are several things IIS has to do (e.g. routing, authentication, and authorization) that ASP.NET can choose to get involved with or not.
ASP.NET is able to control where its custom code is injected into the IIS Request Pipeline by defining its own handlers and modules. Every module gets involved with every request using request pipeline events to tie in. Handlers, on the other hand, work alone. Only one will be chosen to act on a request.
One final thing worth noting is that IIS and ASP.NET can work together in one of two different modes, Classic or Integrated. I won't go into the difference here other than to say that for this answer it doesn't matter which mode you are in. The modes primarily affect how modules execute.
System.Web.UI.Page and IHttpHandler
As mentioned the ASP.NET framework allows you to create your own handlers to extend IIS. Handlers can either be made from scratch or by inheriting from pre-made handlers in the ASP.NET framework.
(Statement 1)The most notable of the pre-made handlers is System.Web.UI.Page. We can tell that this class is a handler because it implements IHttpHandler. This means that every time you create a new aspx page that inherits from System.Web.UI.Page you are creating your own custom handler that will handle a request for that page and return the proper HTML.
(Statement 2)If you'd like to make a handler from scratch you can do so by implementing IHttpHandler on your own classes. This interface only has one method ProcessRequest. When it is time for IIS to pass off to your handler it will call this method and pass the HttpContext for the request you are handling.
(Statement 3) The entire System.Web.UI.Page life-cycle occurs in Page's ProcessRequest method. If you use dotPeek to decompile System.Web.dll you can see everything ProcessRequest does. Some of the more notable things are firing all Page life-cycle events, rendering all WebControls as HTML, and DataBinding. So, in a sense, ProcessRequest is the Page life-cycle (or at least its implementation).
In order to keep this as approachable as possible, I'm going to focus on basic processing in IIS with ASP.NET WebForms and also glaze over some of the more involved details such as HttpModules. Much of this would also apply to an MVC or Apache/Mono environment, with some differences.
When IIS receives a request, it will attempt to match it to an ISAPI filter to handle it. Typically, the matching process is controlled by the extension of the file for the incoming request. In the case of ASP.NET, for example, the .aspx extension is mapped to the .NET ISAPI filter. The .NET ISAPI filter is responsible for processing that request and, under normal circumstances, finds the correct IHttpHandler instance and invokes it to ultimately serve the request. In the case of a WebForm, the match is often as simple as matching the name of the file requested with the page class that implements it.
In ASP.NET, a page is normally derrived from the class System.Web.UI.Page which implements the IHttpHandler interface. IHttpHandler has only a single method, ProcessRequest which the Page class implements for you. Page events and the page life cycle are not known to the handler - those are implementation details of the Page class itself. With respect to your question on the involvement of the HttpHandler during the page lifecycle, there is none. Once the ISAPI filter invokes the ProcessRequest method on the IHttpHandler interface, all other processing and events are a result of the Page class.
This MSDN article, though outdated, provides a reasonable explanation of the high level page rendering pipeline. Please be aware, however, that the details - especially with respect to the page lifecycle and events - have changed significantly since the article was written. (thanks to John Saunders for calling that out in the comments) [Link]
This question is another high level view of HttpHandlers [Link]

HTTP handler vs HTTP module

Can someone explain in less than 2 sentences the difference between both? Yes, I know google can provide hundreds of answers but not one in 2 clear sentences:)
HttpHandler is where the request train is headed. HttpModule is a station along the way.
The two sentences:
An HttpModule will execute for every request to your application, regardless of extension, and is generally used for things like security, statistics, logging, etc.
An HttpHandler is generally associated with a specific extension, and is used for things like RSS feeds, dynamic image generation or modification, and the like.
A little more explanation if that's not completely clear:
The way I think about them - modules "plug in" to the request pipeline, whereas handlers "handle" a specific file extension. So, if you've got a site with a LoggingModule and a PdfHandler, both will execute for a request to http://example.com/sample.pdf, and the logging module alone will execute for a request to http://example.com/page.aspx.
There's a pretty clear article on the difference on MSDN: HTTP Handlers and HTTP Modules Overview
The prime and common goal of HttpHandler and HttpModule is to inject pre-processing logic before the ASP.NET request reaches the IIS Server.
ASP.NET provides two ways of injecting logic in the request pipeline;
Http Handlers:
Http Handler helps us to inject pre-processing logic based on the extension of the file name requested. ASP.NET uses HTTP handlers for implementing a lot of its own functionality.For example, ASP.NET uses handlers for processing .aspx, .asmx and trace.axd files.
example:
RSS feeds: To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. So when users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
There are three steps involved in creating Handler
1. Implement IHttpHandler interface.
2. Register handler in web.config or machine.config file.
3. Map the file extension (*.arshad) to aspnet_isapi.dll in the IIS.
IHttpHandler interface has ProcessRequest method and IsReusable property which needs to be implemented.
ProcessRequest: In this method, you write the code that produces the output for the handler.
IsResuable: This property tells whether this handler can be reused or not.
You can register the handler in web.config file like this
<httpHandlers>
<add verb="*" path="*.arshad" type="namespace.classname, assemblyname" />
</httpHandlers>
Note: here we are handling any file name with extension arshad.
Http Modules:
HttpModule is an event based processor to inject pre-processing logic before the request reaches the IIS Server. ASP.NET uses HTTP Module to implement lots of its own functionality like authentication and authorization, session management and output caching etc.
ASP.NET engine emits lot of events as the request passess through the request pipeline.
Some of those events are AuthenticateRequest, AuthorizeRequest, BeginRequest, EndRequest.
By Using HttpModule you can write logic in these events. These logic get executed as the events fire and before the request reaches IIS.
There are two steps involved in creating Modules,
1. Implement IHttpModule interface
2. Register module in web.config or machine.config file
example:
Security: Using HTTP module, you can perform custom authentication or other security checks before the request reaches IIS.
HTTP handler is the process that runs in response to a request made to an ASP.NET Web application.
HTTP modules let you examine incoming and outgoing requests and take action based on the request.
HttpHandler is responsible for handling http request by extension while HttpModule is responding to application life cycle events.
Nice article aboute it HttpModule-and-HttpHandlers
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”.
HTTP handler is where actually compilation is done based on setting. such as if page extension is .aspx then it will compile through system.web.Ui.Pagahandlefactory. once compilation is done at HTTP handle request will go though HTTP module and IIS.
HTTP Handler
HTTP Handler is the process which runs in response to a HTTP request. So whenever user requests a file it is processed by the handler based on the extension. So, custom http handlers are created when you need to special handling based on the file name extension. Let's consider an example to create RSS for a site. So, create a handler that generates RSS-formatted XML. Now bind the .rss extension to the custom handler.
HTTP Modules
HTTP Modules are plugged into the life cycle of a request. So when a request is processed it is passed through all the modules in the pipeline of the request. So generally http modules are used for:
Security: For authenticating a request before the request is handled.
Statistics and Logging: Since modules are called for every request they can be used for gathering statistics and for logging information.
Custom header: Since response can be modified, one can add custom header information to the response.

Is there No Way to Detect Routed URL in ASP.NET?

Is there no way to detect if the current request is being mapped via ASP.NET 4.0 URL routing?
I have an HTTP module that handles the application's BeginRequest event. I have found that this handler is called for all file types, including CSS, JS, image files, etc., and I just want to perform an action if the target file is an ASPX page.
In the case of routed pages, all the properties of the HttpRequest object reflect the requested URL, and not the ASPX page that the request is being mapped to. How can I determine if the request will be handled by an ASPX file?
Thanks for any suggestions.
Inside of the Begin Request event a Handler has not been defined for the specific URL.
So there is no way of determining what will actually end up handling that URL because IIS has yet to decide. That happens after Begin Request has been fired, that is why all file types are being called.
That's one of the reasons why Begin Request is not a good event to really execute code on that needs to target specifically .NET files. A good use for the Begin Request method is adding cookies or headers to either a request or response. Those can be tacked on without a problem no matter what ends up handling the request.
As mentioned before I would suggest a Base Class that inherits from System.Web.UI.Page that all your other pages inherit from, or create a Master page.
Now without specifically knowing what you are trying to do it's hard to give a good solution. It may be possible to test a URL to check if it'll be fired by a Route, but I don't know how and it also seems excessive when you can handle it through a base class or master page.
You can create a BasePage as a base class for all pages in the application, and handle the Page_Load event there instead of using an HTTP module.

What is the difference between ICallBackEventHandler and HTTPHandler?

When we write our own custom HTTPHandlers aren't they behave the same way as ICallBackEventHanlder does? we use both to make ajax calls from our web page, isn't this correct? or my understanding wrong, I wont doubt if it is :(
Obviously HTTPHandlers are more broader concept since a web page (.aspx) etc are also http handlers.
A ICallBackEventHandler is for integration with a page -- a handler is for anything. A callback handler is useful when you want to do an ajax request from the client-side of a page, and from that handler you still want access to all of the controls on the page, their re-saturated state that comes from ViewState, etc. An http handler has no access to the page or its state. A callback handler can also push some state changes back to the client. For example, a callback handler might render something which requires the __EVENTVALIDATION field on the client-side to be updated.

What is the difference between HttpHandler and a Web User Control and when to use each one?

I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong
Unfortunately your question is a little like "Should I use a sandwich or a cement mixer". HttpHandlers and User controls are completely different things.
HttpHandlers are used to process HTTP requests. For example, if you wanted to dynamically create an RSS feed, you could write an HTTP handler that handles all requests for ".rss" files, creates the output and sends it back to the user.
User controls are used within ASPX pages to encapsulate units of functionality that you want to re-use accross many pages.
Chances are, if you're using user controls successfully, you don't want to use HttpHandlers!
Basically a user control is a piece of server logic and UI. An HTTP Handler is only a piece of logic that is executed when a resource on your server is requested. For example you may decide to handle requests for images sent to your server through your own handler and serve images from a database instead of the file system. However, in this case there's no interface that the user sees and when he visits a URL on your server he would get the response you constructed in your own handler. Handlers are usually done for specific extensions and HTTP request types (POST, GET). Here's some more info on MSDN: http://msdn.microsoft.com/en-us/library/ms227675(VS.80).aspx
Expect a better answer (probably before I finish typing this) but as a quick summary.
A user control is something that can be added to a page.
A HttpHandler can be used instead of a page.
Just to clarify the question. I was reading the Hanselman post
http://www.hanselman.com/blog/CompositingTwoImagesIntoOneFromTheASPNETServerSide.aspx
and thinking that I would never solved the problem with a HttpHandler, maybe with a simple page returning a binary content.
This led me to think that I should add HttpHandler to my developer tool belt.
Even an Asp.Net page is an HttpHandler.
public class Page : TemplateControl, IHttpHandler
A user control actually resides within the asp.net aspx page.

Resources