HTTP module and HTTP handler - asp.net

What are HTTP module and HTTP handler and how do they work while page requesting? How do authentication and authorization processes work in ASP.NET?

Authentication and authorization are events on your Http Pipeline. You can hook on to these modules and do some custom authentication/authorization by making config changes and implementing IHttpModule interface
from msdn:
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
So when IIS receives a request for ".aspx" file, it would tell the aspnet process to handle it. You can configure your own handlers and tell how to handle requests by implementing IHttpHandler interface.
Here is a good low level explanation from Rikh Strahl. Look at this diagram, you can understand them better.
google search can give you a lot of results, but you learn by implementing it :). here is an example. Happy coding.

HTTP handlers are the end point objects in ASP.NET pipeline and an HTTP Handler essentially processes the request and produces the response. For example an ASP.NET Page is an HTTP Handler.
HTTP Modules are objects which also participate the pipeline but they work before and after the HTTP Handler does its job, and produce additional services within the pipeline (for example associating session within a request before HTTP handler executes, and saving the session state after HTTP handler has done its job, is basically done by an HTTP module, SessionStateModule)

Related

Processing request URLs from browser by the .NET Framework

How does the .net framework know in what way the incoming URL is to be processed?
My question is not about routing mechanism within the application.
I want to know how the .net framework in the system finds out that it has to delegate the request to its MVC assemblies to route the URL to appropriate controller and action.
I hope the question is clear.
Just saw some other questions in stackoverflow and came across this link which somewhat explains i guess.
https://docs.google.com/file/d/0B0_EIyBZvSQsOTU3N2Q2NDEtMWNjMS00ZTc0LWJmMjUtM2I0M2I5NDY2ZDNl/edit?pli=1
This link has detailed information
http://stephenwalther.com/archive/2008/03/18/asp-net-mvc-in-depth-the-life-of-an-asp-net-mvc-request
If you host your application in IIS, then when a request comes-in, then this request is initially intercepted by IIS. Let's suppose that you hosted your application in a virtual directory called /myapp. When a request comes by starting with /myapp then IIS will handle the execution of the request to the corresponding ASP.NET pipeline. The ASP.NET pipeline will then parse the incoming request and search for corresponding managed handlers that can serve the request. If a managed handler is found that can serve the request then the processing will be passed to this handler. In the case of as ASP.NET MVC application that will be the MvcHandler which will then take care of routing and dispatching to the appropriate controller and action to serve the request.

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.

Accessing IIS's request handling pipeline to inject a request and get the html response

Is it at all possible to inject a request into IIS for a page, have IIS and ASP.Net handle it as normal, but get the response as html handed back to me programmatically?
Yes, I know that I could connect to port 80 using WebRequest and WebResponse, but that becomes difficult if you are accessing the IIS server from the same physical machine (loopback security controls et al).
Basically, I want to inject the request (eg for http://example.org/MyPage.aspx) between the points at which IIS would normally talk to the browser, and the point at which it would route it to the correct ASP.Net application, and get a response back from IIS between the points at which ASP.Net/IIS applies the httpfilters and hands the html back to the browser.
I'm predominantly working with IIS7 so if there is a solution that works just for IIS7 then thats not an issue.
You could implement a custom HttpModule, which would give you access to the IIS pipeline, including the final response. However, you would still need to initiate a request to IIS to actually kick off processing. Not sure if this would work for you.
From the MSDN documentation:
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 request pipeline
and have access to life-cycle events
throughout the request. HTTP modules
therefore let you examine incoming
requests and take action based on the
request. They also let you examine the
outgoing response and modify it.
Gave you looked into the WebCkiebt class? You can make the request and get the response HTML.
http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadstring(v=VS.100).aspx

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.

IIS - Different processing of default document in Integrated Pipeline mode?

I have an HTTP Module to handle authentication from Facebook, which works fine in classic pipeline mode.
In integrated pipeline mode, however, I'm seeing an additional request pass through for the default document, which is causing the module to fail. We look at the request (from Facebook) to retrieve and validate the user accessing our app. The initial request authenticates fine, but then I see a second request, which lacks the posted form variables, and thus causes authentication to fail.
In integrated pipeline mode, an http request for "/" yields 2 AuthenticateRequests in a row:
A request where AppRelativeCurrentExecutionFilePath = "~/"
A request where AppRelativeCurrentExecutionFilePath = "~/default.aspx"
That second request loses all of the form values, so it fails to authenticate. In classic mode, that second request is the only one that happens, and it preserves the form values.
Any ideas what's going on here?
UPDATE: Here is an image of the trace from module notifications in IIS. Note that my module, FBAuth, is seeing AUTHENTICATE_REQUEST multiple times (I'd expect 2 - one for authenticate and one for postauthenticate, but I get 4).
I'm starting to believe this has something to do with module/filter configuration because I've found a (Vista) box running the same code that doesn't fire these events repeatedly - it behaves as expected. I'm working through trying to figure out what the difference could be...
Thanks!
Tom
My solution was to add the following code at the end of Application_BeginRequest:
if (Request.RawUrl.TrimEnd('/') == HostingEnvironment.ApplicationVirtualPath.TrimEnd('/'))
Server.Transfer(Request.RawUrl+"Default.aspx", true);
DefaultHttpHandler is not supported,
so applications relying on sub-classes
of DefaultHttpHandler will not be able
to serve requests If your application
uses DefaultHttpHandler or handlers
that derive from DefaultHttpHandler,
it will not function correctly. In
Integrated mode, handlers derived from
DefaultHttpHandler will not be able to
pass the request back to IIS for
processing, and instead serve the
requested resource as a static file.
Integrated mode allows ASP.NET modules
to run for all requests without
requiring the use of
DefaultHttpHandler. Workaround
Change your application to use
modules to perform request processing
for all requests, instead of using
wildcard mapping to map ASP.NET to all
requests and then using
DefaultHttpHandler derived handlers to
pass the request back to IIS.
Hmmm, or this could be the issue.
ASP.NET modules in early request
processing stages will see requests
that previously may have been rejected
by IIS prior to entering ASP.NET,
which includes modules running in
BeginRequest seeing anonymous requests
for resources that require
authentication ASP.NET modules can run
in any pipeline stages that are
available to native IIS modules.
Because of this, requests that
previously may have been rejected in
the authentication stage (such as
anonymous requests for resources that
require authentication) or other
stages prior to entering ASP.NET may
run ASP.NET modules. This behavior is
by design in order to enable ASP.NET
modules to extend IIS in all request
processing stages. Workaround
Change application code to avoid
any application-specific problems that
arise from seeing requests that may be
rejected later on during request
processing. This may involve changing
modules to subscribe to pipeline
events that are raised later during
request processing.
http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/

Resources