When HttpModule Init method runs in ASP.NET Integrated mode? - c#

I've written an HttpModule that is an NHibernate Session Provider. It simply opens a SessionFactory in Init method of HttpModule and gets a new Session in BeginRequest and closes it in EndRequest. At the other side, I wrote a method in Global.asax that uses a session from this HttpModule named GetData. I run that method (GetData) in Init method of Global.asax. The problem is when I use my HttpModule in integrated mode it seems that my HttpModule does not Initialize before running Init method of Global.asax.
I've searched for order of running these methods and life cycle of events but nothing useful found!

In IIS 7.x, modules and handlers should be registered within system.webServer xml element in your web.config file.
Check this MSDN article:
http://msdn.microsoft.com/en-us/library/ms227673.aspx

ASP.NET does not provide any guarantees on when HttpModule Init() methods are called with respect to one another (not unlike static initializers). In general, the Init() methods should be used to wire up event handlers, and any "real work" should be done in the event handlers.
All registered event handlers for a specific event are called from all HttpModules, including Global.asax, before moving on to the next event -- so you have control over order that way.

Related

How do I add an event handler for every request in ASP.NET that will be handled by PageHandlerFactory

I want to configure an asp.net website so that for every request it executes my event handler(say for tracking/logging some info from request object) only if request will be handled by an PageHandlerFactory.
I know I can write it in Application_BeginRequest but that is called for every kind of request(be it *.axd or so ,Correct me if I'm wrong here). HttpContext.Current.CurrentHandler might be null at this time so I can't put conditional logic for handler type. For some reason(legacy business rules/checks) I can't move the my logic to Application_EndRequest.
Use can try using the httphandler and httpmodule in asp.net
it has an event LogRequest
LogRequest - Occurs just before ASP.NET performs any logging for
the current request. The LogRequest event is raised even if an error
occurs. You can provide an event handler for the LogRequest event to
provide custom logging for the request.
Furthure in ASP.net we have
ASP.NET uses different HTTP handlers to serve different file types.
For example, the handler for web Page creates the page and control
objects, runs your code, and renders the final HTML. ASP.NET default
handlers:
1) Page Handler (.aspx) – Handles Web pages 2) User Control Handler
(.ascx) – Handles Web user control pages 3) Web Service Handler
(.asmx) – Handles Web service pages 4) Trace Handler (trace.axd) –
Handles trace functionality
You can get more insight at
httphandler and httpmodule in asp.net

Confused over global.asax?

I have a class called Global that derives from HttpApplication.
Oddly, I see a lot of methods inside Global that look like:
void Application_Start(object sender, EventArgs e)
{
}
The code is definitely executing inside this method, so the method is being called from somewhere, but where? The methods aren't marked overload?
Secondly, I derived a class from Global, let's call it GlobalFoo.
Again, if I create a method called Application_Start() it will get called inside my derived class, otherwise nothing that's in Global will get called so I might as well be deriving from an empty class.
Can anyone offer any advice? Am I missing some fundamental part of ASP.NET?
so the method is being called from somewhere, but where?
This functions are called from the Application Pool (from each pool that you have assign), to signal start-up/end events of your application and help your with initializations.
Every pool that is assign to run your web application runs those functions.
asp.net is helping you create different objects/code external or not that can run together, and that's why you see that all of your registered code run. Its a help to create more than one "start up" routines that do different thinks.
This is an example, this module just check the secure protocol by him self... and you do not need to change anything on your code, just register it.
IIS calls the different Global.asax events through the asp.net isapi filter.
Perhaps this article will help explain.
The Global.asax file is an optional file used to declare and handle application and session-level events and objects for an ASP.NET web site running on an IIS Web Server
some of the key events in this file are:
Application_Init: Fires when the application initializes for the first time.
Application_Start: Fires the first time an application starts.
Session_Start: Fires the first time when a user’s session is started.
Application_BeginRequest: Fires each time a new request comes in.
Application_EndRequest: Fires when the application terminates.
Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
Application_Error: Fires when an unhandled error occurs within the application.
Session_End: Fires whenever a single user Session ends or times out.
Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).
For a complete list of Global.asax events see "Global.asax Events".

What is the purpose of global.asax in asp.net

How can we use global.asax in asp.net? And what is that?
MSDN has an outline of the purpose of the global.asax file.
Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.
You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):
Application_Start
Application_End
Session_Start
Session_End
Application_BeginRequest
Application_AuthenticateRequest
Application_Error
There are other events that you can also hook into, such as "LogRequest".
Global asax events explained
Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.
Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.
Application_Error: Fired when an unhandled exception is encountered within the application.
Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.
Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.
Application_EndRequest: The last event fired for an application request.
Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.
Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.
Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).
Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).
Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.
Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.
Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.
Session_Start: Fired when a new user visits the application Web site.
Session_End: Fired when a user's session times out, ends, or they leave the application Web site.
The Global.asax file, also known as
the ASP.NET application file, is an
optional file that contains code for
responding to application-level and
session-level events raised by ASP.NET
or by HTTP modules.
http://msdn.microsoft.com/en-us/library/2027ewzw.aspx
Global.asax is the asp.net application file.
It is an optional file that handles events raised by ASP.NET or by HttpModules. Mostly used for application and session start/end events and for global error handling.
When used, it should be in the root of the website.
The root directory of a web application has a special significance and certain content can be present on in that folder.
It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a
class at runtime which is inherited from HttpApplication.
During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When
an application receives an http request, the ASP.Net page framework assigns one of these instances to process that
request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance
can only be reused after the request has been completed when it is returned to the pool.
The instance members in Global.asax cannot be used for sharing data across requests but static member can be.
Global.asax can contain the event handlers of HttpApplication object and some other important methods which
would execute at various points in a web application
The Global.asax can be used to handle events arising from the application. This link provides a good explanation: http://aspalliance.com/1114

IHttpHandler vs IHttpModule

My question is simple (although the answer will most likely not be): I'm trying to decide how to implement a server side upload handler in C# / ASP.NET.
I've used both HttpModules (IHttpModule interface) and HttpHandlers (IHttpHandler interface) and it occurs to me that I could implement this using either mechanism. It also occurs to me that I don't understand the differences between the two.
So my question is this: In what cases would I choose to use IHttpHandler instead of IHttpModule (and vice/versa)?
Is one executed much higher in the pipeline? Is one much easier to configure in certain situations? Does one not work well with medium security?
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.
Typical uses for custom HTTP handlers include the following:
RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.
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.
Typical uses for HTTP modules include the following:
Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
From: http://msdn.microsoft.com/en-us/library/bb398986.aspx
As stated here, HttpModules are simple classes that can plug themselves into the request processing pipeline, whereas HttpHandlers differ from HttpModules not only because of their positions in the request processing pipeline, but also because they must be mapped to a specific file extensions.
IHttpModule gives you much more control, you can basically control all of the traffic directed to your Web application. IHttpHandler gives you less control (the traffic is filtered before it reaches your handler), but if this is sufficient for your needs, then I see no reason to use the IHttpModule.
Anyway, it's probably best to have your custom logic in a separate class, and then just use this class from either IHttpModule or IHttpHandler. This way you don't really have to worry about choosing one or the other. In fact, you could create an extra class which implements both IHttpHandler and IHttpModule and then decide what to use by setting it in Web.config.
15 seconds has a nice small tutorial giving practical example
Modules are intended to handle events raised by the application before and after the request is actually processed by the handler. Handlers, on the other hand, aren't given the opportunity to subscribe to any application events and, instead, simply get their ProcessRequest method invoked in order to the "main" work of processing a specific request.
Take a look at this documentation from Microsoft (about half way down the page in the "The request is processed by the HttpApplication pipeline" section):
http://msdn.microsoft.com/en-us/library/bb470252.aspx
You can see in step 15 where the handler gets its chance to execute. All of the events before and after that step are available for interception by modules, but not handlers.
Depending on what specific features you're trying to achieve, you could use either a handler or a module to implement an upload handler. You might even end up using both.
Something to consider might to use an upload handler that's already written.
Here's a free and open source one:
http://www.brettle.com/neatupload
Here's a commercial one:
http://krystalware.com/Products/SlickUpload/
If you look at the documentation for NeatUpload, you'll see that it requires you to configure a module.

What's the performance difference between HttpModule and Global.aspx?

I have made a web app where I am using a module which redirects without "www" urls (http://example.com/) to with "www" urls (http://www.example.com/). But as I am on shared hosting server, where I don't have permission to implement a HttpModule, then I tried the same module code with Global.asax file. That works!
I used the following (Application_BeginRequest()) event to implement my HttpModule functionality.
void Application_BeginRequest()
{
//module code
}
The module and application is working well and correctly from Global.asax file But I am worried about the performance.
Why we use the HTTPModules in asp.net If we can implement the same using Global.asax file. Is there ay performance differences between both. Or any difference about which I need to worry about when using Global.asax file instead of HttpModule ??
Please explain!
Global.asax inherits from HTTPApplication, and HTTPModules must implement the IHTTPInterface.
The HTTPModules Init method gets the HTTPApplication object passed in.
In the Init method you can hook into the events of HTTPApplication.
I would recommend to use HTTPModules wherever you can.
Especially if you make shrink-wrapped software where the customer can replace your global.asax with their own.
There is pretty much no difference. The point of HTTPModules is for clarity and seperation. Often people will pipe the request through several HTTPModules, which is something you can't get with global.asax.

Categories

Resources