472,804 Members | 1,121 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,804 software developers and data experts.

Using HttpModules instead of Global.asax

Global.asax? Use HttpModules Instead!
In a previous post, I talked about HttpHandlers - an underused but
incredibly useful feature of ASP.NET. Today I want to talk about
HttpModules, which are probably more common than HttpHandlers, but
could still stand to be advertised a bit more.

HttpModules are incredibly easy to explain, so this will hopefully be a
short-ish post. Simply put, HttpModules are portable versions of the
global.asax. So, in your HttpModule you'll see things like
BeginRequest, OnError, AuthenticateRequest, etc. Actually, since
HttpModules implement IHttpModule, you actually only get Init (and
Dispose if you have any cleanup to do). The Init method passes in the
HttpApplication which lets you hook into all of those events. For
example, I have an ErrorModule that I use on most projects:

using System;
using System.Web;
using log4net;

namespace Fuel.Web
{
public class ErrorModule : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication application)
{
application.Error += new EventHandler(application_Error);
}
public void Dispose() { }
#endregion

public void application_Error(object sender, EventArgs e)
{
//handle error
}
}
}

Now, the code in my error handler is pretty simple:

HttpContext ctx = HttpContext.Current;
//get the inner most exception
Exception exception;
for (exception = ctx.Server.GetLastError(); exception.InnerException !=
null; exception = exception.InnerException) { }
if (exception is HttpException &&
((HttpException)exception).GetHttpCode() == 404)
{
logger.Warn("A 404 occurred", exception);
}
else
{
logger.Error("ErrorModule caught an unhandled exception", exception);
}

I'm just using a log4net logger to log the exception, if it's a 404 I'm
just logging it as a warning.

You can do this just as easily with a global.asax, but those things
aren't reusable across projects. That of course means that you'll end
up duplicating your code and making it hard to manage. With my
ErrorModule class, I just put it in a DLL, drop it in my bin folder and
add a couple lines to my web.config under <system.web>:

<httpModules>
<add name="ErrorModule" type="Fuel.Web.ErrorModule, Fuel.Web" />
</httpModules>

And voila, I have a global error in place.

In almost all cases, you should go with HttpModules over global.asax
because they are simply more reusable. As another example, my
localization stuff uses an HttpModule as the basis for adding a
multilingual framework to any application. Simply drop the DLL in the
bin and add the relevant line in your web.config and you're on your
way. Here's the important code from that module:

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose() {}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpRequest request = ((HttpApplication) sender).Request;
HttpContext context = ((HttpApplication)sender).Context;
string applicationPath = request.ApplicationPath;
if(applicationPath == "/")
{
applicationPath = string.Empty;
}
string requestPath =
request.Url.AbsolutePath.Substring(applicationPath .Length);
//just a function that parses the path for a culture and sets the
CurrentCulture and CurrentUICulture
LoadCulture(ref requestPath);
context.RewritePath(applicationPath + requestPath);
}

If you are developing a shrink-wrap product, you don't have a choice
but to use HttpModules, because the last thing you want is to ship a
global.asax which the user must use, overwriting the code in his own
global.asax.

The only time you want to use Global.asax is when using OutputCaching
with the VaryByCustom property. As far as I know, the
GetVaryByCustomString function _must_ be placed in the global.asax
file.

Anyways, switching from Global.asax to HttpModules is pretty
straightforward. So I encourage you to look at where it makes sense
(ie, where you see the potential for reuse across applications) and
make it so.

Jun 15 '06 #1
1 3188
Is there a reason you're trying to pass off someone else's work as your own?
As the author for these three pieces, I'm glad you saw value in what I
wrote, but don't appreciate having it spammed in a help newsgroup (which I
happen to spend a lot of time in) and I don't appreciate you not linking
back to the original content.

http://codebetter.com/blogs/karlseguin/

--
http://www.openmymind.net/
http://www.fuelindustries.com/
"Anonieko" <an******@hotmail.com> wrote in message
news:11*********************@i40g2000cwc.googlegro ups.com...
Global.asax? Use HttpModules Instead!
In a previous post, I talked about HttpHandlers - an underused but
incredibly useful feature of ASP.NET. Today I want to talk about
HttpModules, which are probably more common than HttpHandlers, but
could still stand to be advertised a bit more.

HttpModules are incredibly easy to explain, so this will hopefully be a
short-ish post. Simply put, HttpModules are portable versions of the
global.asax. So, in your HttpModule you'll see things like
BeginRequest, OnError, AuthenticateRequest, etc. Actually, since
HttpModules implement IHttpModule, you actually only get Init (and
Dispose if you have any cleanup to do). The Init method passes in the
HttpApplication which lets you hook into all of those events. For
example, I have an ErrorModule that I use on most projects:

using System;
using System.Web;
using log4net;

namespace Fuel.Web
{
public class ErrorModule : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication application)
{
application.Error += new EventHandler(application_Error);
}
public void Dispose() { }
#endregion

public void application_Error(object sender, EventArgs e)
{
//handle error
}
}
}

Now, the code in my error handler is pretty simple:

HttpContext ctx = HttpContext.Current;
//get the inner most exception
Exception exception;
for (exception = ctx.Server.GetLastError(); exception.InnerException !=
null; exception = exception.InnerException) { }
if (exception is HttpException &&
((HttpException)exception).GetHttpCode() == 404)
{
logger.Warn("A 404 occurred", exception);
}
else
{
logger.Error("ErrorModule caught an unhandled exception", exception);
}

I'm just using a log4net logger to log the exception, if it's a 404 I'm
just logging it as a warning.

You can do this just as easily with a global.asax, but those things
aren't reusable across projects. That of course means that you'll end
up duplicating your code and making it hard to manage. With my
ErrorModule class, I just put it in a DLL, drop it in my bin folder and
add a couple lines to my web.config under <system.web>:

<httpModules>
<add name="ErrorModule" type="Fuel.Web.ErrorModule, Fuel.Web" />
</httpModules>

And voila, I have a global error in place.

In almost all cases, you should go with HttpModules over global.asax
because they are simply more reusable. As another example, my
localization stuff uses an HttpModule as the basis for adding a
multilingual framework to any application. Simply drop the DLL in the
bin and add the relevant line in your web.config and you're on your
way. Here's the important code from that module:

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose() {}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpRequest request = ((HttpApplication) sender).Request;
HttpContext context = ((HttpApplication)sender).Context;
string applicationPath = request.ApplicationPath;
if(applicationPath == "/")
{
applicationPath = string.Empty;
}
string requestPath =
request.Url.AbsolutePath.Substring(applicationPath .Length);
//just a function that parses the path for a culture and sets the
CurrentCulture and CurrentUICulture
LoadCulture(ref requestPath);
context.RewritePath(applicationPath + requestPath);
}

If you are developing a shrink-wrap product, you don't have a choice
but to use HttpModules, because the last thing you want is to ship a
global.asax which the user must use, overwriting the code in his own
global.asax.

The only time you want to use Global.asax is when using OutputCaching
with the VaryByCustom property. As far as I know, the
GetVaryByCustomString function _must_ be placed in the global.asax
file.

Anyways, switching from Global.asax to HttpModules is pretty
straightforward. So I encourage you to look at where it makes sense
(ie, where you see the potential for reuse across applications) and
make it so.

Jun 15 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Faisal | last post by:
Hi. I'm in the process of moving an application from ASP to ASP.NET, & I'm writing in VB, using VS.NET. I'm new to the .NET framework & have a basic question regarding static objects defined in...
1
by: Ian Turner | last post by:
Hi, Is there anyway, without dropping back to C++ and ISAPI filters, whereby I can route requests to virtual url paths through to the ASPNET runtime and ultimately processed by an HttpModule? ...
2
by: Aurel | last post by:
Hi, I have create a httpmodule but I have some problems. I can't access to the session. Even if I create my class like this public class myModule: IHttpModule, IRequiresSessionState {} ...
3
by: msnews.microsoft.com | last post by:
Hi... I'm learning about HTTPModules, so please allow me a beginner's question. I read that "you gain low-level access to the HTTPRequests and responses processed by the ASP.NET framework"....
12
by: John M | last post by:
Hello, On Microsoft Visual Studio .NET 2003, I want to use some global elements, that can be used in each one of my pages. i.e I put a oleDBConnection on global.asax.vb How can I use it...
2
by: tshad | last post by:
I am setting up Authentication that I want to put in multiple Web Sites on my server. I found a good article on this and am looking at moving my code from my Global.asax file to an HTTP Module. ...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
8
by: Victor | last post by:
Can I get the events in GLOBAL.ASAX to fire if a classic ASP page is being accessed by the user?
1
by: Samuel R. Neff | last post by:
We have a problem with Web.config inheritance in two of our applications. We have an old app which is poorly written and must be in the root of the server. We have a newer app which runs from a...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.