Process Request method in Page Life Cycle - asp.net

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]

Related

TransferRequest vs Transfer in ASP.Net

I have gone through the links mentioned below,
iis forum and HttpModules & Server.Transfer / Server.TransferRequest / RewritePath problems. but unable to catch the concept behind these transfer methods.
How are they works? And which one is preferred in different situation?
Can someone explain me TransferRequest vs Transfer methods for server side transfer in asp.net and its roles?
Thanks in advance
HttpServerUtility.Transfer Terminates execution of the current page and starts execution of provided URL.
This basically maps and executes a new ASP.NET Page (or serves a static file) corresponding to the url provided. It does this in-place in the current request pipeline, without applying new configuration to the new url, or re-running IIS modules for the new url. Because of this, its very fast, but it also prevents a lot of scenarios that are possible with TRQ.
HttpServerUtility.TransferRequest Performs an asynchronous execution of the provided URL.
This is a full IIS child request under the covers, which allows it to re-run the entire request pipeline for the new request as if it was a separate request, getting the correct configuration for it, and running all of the normal IIS modules including authentication, authorization, etc. For example, IIS will apply the authorization rules for the new url, as opposed to the previous url.
TransferRequest re-runs the entire request pipeline as if it were a separate request. This means that IIS and ASP.NET modules are re-applied; authentication and authorization rules for the new URL will be honored. Note that TransferRequest requires the integrated pipeline mode of IIS 7+, and the transfer can be to an ASP page or another resource like an XML file.
Transfer transfers execution from one ASP page to another ASP page on the server. Unlike TransferRequest, IIS and ASP.NET will NOT verify that the current user is authorized to view the resource delivered by the Transfer method. If you need to force reauthorization, and integrated pipeline mode is not an option, call Redirect instead of the Transfer method. Redirect triggers a client-side redirect so that the new request will be subjected to all authentication and authorization logic of IIS and ASP.NET.

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.

When to use HttpHandlers and HttpModules?

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).

http handlers and modules: what's a good example of a problem they solve?

I got this in an interview question -- the question was more about what they do, which I didn't know beyond very vague terms. But after reading about them I'm still no closer to an understanding of what problems I would solve with an HttpHandler or HttpModule. I've worked a fair amount in ASP.NET but it's been a few years -- is this a large gap in my knowledge? Something that's been replaced by more current technology?
Clarification: what's a common problem in the ASP.NET world that would be much easier to solve with an HttpHandler as opposed to something you'd do in a webservice or an ajax call?
Believe it or not ASP.NET is built using HTTP handlers and HTTP modules to provide default ASP.NET behavior. For a good write-up, please see HTTP Handlers and HTTP Modules Overview:
An ASP.NET HTTP handler is the process
(frequently referred to as the
"endpoint") that runs in response to a
request made to an ASP.NET Web
application. 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. You can create your own HTTP
handlers that render custom output to
the browser.
An HTTP module is an assembly that is
called on every request that is made
to your application. HTTP modules are
called as part of the ASP.NET request
pipeline and have access to life-cycle
events throughout the request. HTTP
modules let you examine incoming and
outgoing requests and take action
based on the request.

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