Config-free IHttpModule Registration

Simplifying framework components that plug into the ASP.NET HTTP pipeline by registering HttpModules programmatically without any configuration using a new, hidden ASP.NET 4 feature.

HTTP Request Processing PipelineThe ASP.NET pipeline allows HTTP modules to plug in into the request processing lifecycle and do work at various stages. For example, output caching, authentication, authorization etc. are all implemented as HTTP modules.

However one of the problems is that HTTP modules must be registered in configuration. This is a little painful for writing framework components where an HTTP module is essentially an implementation detail. You don't want every app developer using your framework to have to add in some configuration entries. What you want is the ability to programmatically add HTTP modules to the pipeline. This isn't available out-of-the-box today.

I faced this problem in my previous post around RIA Services, Authentication and Roles, as I needed to handle the PostAuthenticateRequest event. This seems to have come up before (for example here and here on stack overflow).

So in the interim, we can use the new, and somewhat obscure, ASP.NET 4.0 feature, the PreApplicationStartMethodAttribute, that lets you declare some code you want to run early in the initialization phase of your web application, even before any dynamic compilation happens and before any application startup code runs. Combine that capability with an HttpApplication that supports registering HTTP modules programmatically, as we're in business. I wrote DynamicHttpApplication that provides this API (link to code below):

public abstract class DynamicHttpApplication : HttpApplication {
    public static void RegisterModule(Func<HttpApplication, IHttpModule> moduleFactory);
}

You'll need to use this class as your base class in Global.asax.cs in your web app instead of the default which is HttpApplication.

With this in place, I can add a class library as a reference, or place it in the bin directory and programmatically register HTTP modules without requiring additional configuration. For example, say I have a user tracking HTTP module that does something interesting with the authenticated user. Here's the code I can write:

[assembly: PreApplicationStartMethod(typeof(UserTrackerModule), "Register")]

namespace DynamicWebApp.Sample {

    public sealed class UserTrackerModule : IHttpModule {

        #region Implementation of IHttpModule
        void IHttpModule.Dispose() {
        }

        void IHttpModule.Init(HttpApplication application) {
            application.PostAuthenticateRequest += delegate(object sender, EventArgs e) {
                IPrincipal user = application.Context.User;

                if (user.Identity.IsAuthenticated) {
                    DateTime activityDate = DateTime.UtcNow;

                    // TODO: Use user.Identity and activityDate to do
                    //       some interesting tracking
                }
            };
        }
        #endregion

        public static void Register() {
            DynamicHttpApplication.RegisterModule(delegate(HttpApplication app) {
                return new UserTrackerModule();
            });
        }
    }
}

Basically it is a normal/typical IHttpModule implementation that you might write with one thing extra: a static Register method that is declared to be the PreApplicationStartMethod in the assembly's metadata.

HTTP modules provide powerful ways to do interesting things in ASP.NET. For example, we do some pretty creative things in RIA Services with our HTTP module. The ASP.NET infrastructure lets framework components do their job, and now they can do so without needing ugly configuration entries.


Links

Source code containing the DynamicHttpApplication (its fairly simple ... implemented in around ~50 lines of code) that you can use in your own app, along with the sample above.


[ Tags: | ]
Posted on Thursday, 7/1/2010 @ 7:29 AM | #ASP.NET


Comments

25 comments have been posted.

Rahul Soni

Posted on 7/1/2010 @ 9:25 AM
That was really smart. It is so funny, if somebody would have asked about this question from me yesterday, I would have simply said "I don't think it could be done!"

Thank you so much for sharing this Nikhil!!!!

Mahesh Velaga

Posted on 7/2/2010 @ 3:02 AM
Nice Snippet and a great idea !

As a side note, I would use ".Any()" instead of ".Count == 0" for checking if there are any elements in that IEnumerable.

Nikhil Kothari

Posted on 7/2/2010 @ 4:32 PM
@Mahesh

I had a List in the code as opposed to an IEnumerable, and so Count is a more direct way than Any() which I believe checks for a List as well and resorts to Count in that case...

Ruben Prins

Posted on 7/7/2010 @ 4:22 AM
Nice; however, something tells me this is rather fragile. For instance, the recently released Razor engine also requires its own HttpApplication-derived Global.asax (for hooking up its web page routing support, so details.cshtml can be accessed though details/123, and registering its build providers). In fact, it even registers its HttpApplication-class in the PreApplicationStartMethod by setting PageParser.DefaultApplicationBaseType. Which even makes it a no-code solution, too! (Don't you just love Reflector?) Which I guess means it cannot work together with this solution.

Wouldn't it be better if there were a couple of static events within the core of ASP.NET like HttpApplication.BeforeInit/AfterInit? That way each PreApplicationStartMethod could hook up cleanly, which does not seem possible this way. Being able to register IHttpModules and IHttpHandlers programmatically would also solve this, I guess.

Nikhil Kothari

Posted on 7/8/2010 @ 1:31 AM
@Ruben
The sample represents what you can do today, based on limitations of the core platform.

Yes, of course things can be done to add this capability in the core platform, and that will happen undue course of time. Meanwhile, the problem/scenario exists and some solution is interesting. Also in the meanwhile, multiple solutions to the same problem like the Razor one probably can't coexist, since they're both trying to do the same thing! :)

Miguel Fernandes

Posted on 7/15/2010 @ 6:45 AM
This is an interesting approach!

How can I get the client call to Autentication.LoadUser to work, so it can remember the last logged in user?
My guess is the FormsAuthenticationService implementation of GetUser should look at the _ASPXAUTH cookie and return the deserialized user, or is there a better way to do it?

Nikhil Kothari

Posted on 7/20/2010 @ 10:22 PM
@Miguel
When you call Authentication.GetUser it looks at the currently authenticated principal, which will cause FormsAuthenticationService to deserialize a User object from the forms auth ticket stored in the forms auth cookie.

Tyrone Davis

Posted on 7/25/2010 @ 4:17 PM
I'm you use a lamba expression to shorten the registration code to this?

public static void Register() {
DynamicHttpApplication.RegisterModule((app) => return new UserTrackerModule());
}

However, this was a nice tip indeed. Thanks

Miguel Fernandes

Posted on 7/27/2010 @ 3:47 AM
Turned out to be a cookie persistence problem, the expiration time was not being passed along.
Solved it by setting the cookie expiration time in FormsAuthenticationService.Login like this:

authCookie.Expires = ticket.Expiration;

Tariq Azam

Posted on 9/19/2010 @ 5:43 PM
That is awesome. Thanks for the tip.

Mohammad Rafey

Posted on 9/20/2010 @ 11:49 PM
This is an interesting workaround with some limitations..!!

Mohammad Rafey

Posted on 9/28/2010 @ 3:03 AM
Works well with .NET Framework 4.0 where in we can plug some custom HTTPModules in ASP.NET Request Processing Pipeline, I was wondering is there any or similar workaround we can achieve in .NET 3.0/3.5 where we don't have "PreApplicationStartMethodAttribute" option. I dont want multiple developers working on the same application entering there respective HTTPModules entries in web.config file.

Please suggest..

akverma

Posted on 10/27/2010 @ 7:55 AM
I think solves lot of issue I've faced in order to use any component we had to add configs and sometimes it uses to cause issue for other developer not being aware of how to add it to config. but have one question wouldn;t this have any impact on performance as this would be registering for every component that you write?

Tomás Corellano

Posted on 4/6/2011 @ 1:21 PM
Awesome implementation, that ASP.NET 4 feature blew my mind.

I'm using your module in an MVC3 application with razor that uses IoC to load implementetions of data access. since my implementation uses NHibernate I needed a way to add an httpmodule to handle the hibernate session on a per request basis.

Your code worked out of the box with MVC3, and Razor, just by having the dll with the HttpModule implementation put under the bin folder (There's no direct reference in the WebProject)

Thanks!!

fitflop Gogh Clogs

Posted on 5/23/2011 @ 11:18 PM
You can buy cheap <a href="http://www.fitflopoutlet.com">Fitflop Gogh clogs</a> on sale online with as much as 30% off selected sizes. All the colours and types including the ever popular chocolate and brown ones. These are some of the most popular types of footwear that Fitflop do and you wont be surprised to know have been selling like hot cakes all over the world.

Discount Fiflop Gogh Clogs really are some of the most comfortable footwear you could ever own. If you spend a large part of your day on your feet or walking then you will often know your feet, legs and sometimes even your back can ache at the end of the day. This is normally because the footwear you are wearing isn’t giving you sufficient support. Try out some clogs and you will be pleasantly surprised with the improvement that you feel.

The unique selling point of the profession design <a href="http://www.fitflopoutlet.com">FitFlop Gogh Clogs</a> are that they can aid you in getting fit. Just walking in these will help you get fit due to the specialised mid sole that will challenge your feet and tone them with every step. The personality design of <a href="http://www.fitflopoutlet.com">Fitflop Gogh clogs</a> even feature faux sheepskin to add to the comfort.

Sounds good but what do customers think?

Well this has been one of the highest rated and best selling clogs online at sites such as Amazon. The customer feedback has also been terrific.Many of people have commented that these really are the most comfortable shoes you will ever wear. We have heard from people who have to work retail jobs which require them to be on their feet all day and they say these are like a blessing to them. If you have to stand all day and constantly end the day with aching feet then these will get rid of that problem. There are some that even said the shoes really helped with the problems they had in their lower back.

Some people even bought these just for the cool look. These can be a great casual shoe to wear if going out shopping or to meet friends for coffee.The shoes appear to be really durable too with many people saying they got at least a few years wear out of them before having to buy a new pair. So at such an affordable price these seem well worth it. These really will make both your work and social life much better!

fitflop Gogh Clogs

Posted on 5/23/2011 @ 11:19 PM
You can buy cheap <a href="http://www.fitflopoutlet.com">Fitflop Gogh clogs</a> on sale online with as much as 30% off selected sizes. All the colours and types including the ever popular chocolate and brown ones. These are some of the most popular types of footwear that Fitflop do and you wont be surprised to know have been selling like hot cakes all over the world.

Discount Fiflop Gogh Clogs really are some of the most comfortable footwear you could ever own. If you spend a large part of your day on your feet or walking then you will often know your feet, legs and sometimes even your back can ache at the end of the day. This is normally because the footwear you are wearing isn’t giving you sufficient support. Try out some clogs and you will be pleasantly surprised with the improvement that you feel.

The unique selling point of the profession design <a href="http://www.fitflopoutlet.com">FitFlop Gogh Clogs</a> are that they can aid you in getting fit. Just walking in these will help you get fit due to the specialised mid sole that will challenge your feet and tone them with every step. The personality design of <a href="http://www.fitflopoutlet.com">Fitflop Gogh clogs</a> even feature faux sheepskin to add to the comfort.

Sounds good but what do customers think?

Well this has been one of the highest rated and best selling clogs online at sites such as Amazon. The customer feedback has also been terrific.Many of people have commented that these really are the most comfortable shoes you will ever wear. We have heard from people who have to work retail jobs which require them to be on their feet all day and they say these are like a blessing to them. If you have to stand all day and constantly end the day with aching feet then these will get rid of that problem. There are some that even said the shoes really helped with the problems they had in their lower back.

Some people even bought these just for the cool look. These can be a great casual shoe to wear if going out shopping or to meet friends for coffee.The shoes appear to be really durable too with many people saying they got at least a few years wear out of them before having to buy a new pair. So at such an affordable price these seem well worth it. These really will make both your work and social life much better!

fitflop Gogh Clogs

Posted on 5/23/2011 @ 11:19 PM
[url=http://www.fitflopoutlet.com]Fashionable FitFlop[/url] is famous for those sandals that tone legs and glutes while you walk, and they’ve stepped up their style game with the hottest silhouette of the season – now you can wear the hot clog trend and improve your fitness at the same time. Slick patent leather forms the upper, with hardware-chic studs lining the edge. “[url=http://www.fitflopoutlet.com]Microwobbleboard[/url]” midsoles keep your muscles working with every step.

Created in the UK, over a two-year collaboration between former Bliss spa-entrepreneur Marcia Kilgore, Biomechanist Dr. David Cook and a team of untiring footwear engineers, FitFlops Gogh Clogs were initially designed to help modern women squeeze a little more exercise into their increasingly hectic schedules."I thought, how amazing if I could invent something that would help fight the onset of cellulite while I'm walking to the office," says Kilgore. "I work. I have kids. I have a husband. with the likelihood of me seeing the inside of a gym in the next ten years is slim to none. That said, I'd obviously prefer to go with slim." Kilgore found Dr. Cook at The Centre for Human Performance at London's LSBU, where he envisioned injecting the patent-pending 'microwobbleboard' technology into the midsole of the function-forward flip flop. Slightly destabilizing,Amazing excogitation [url=http://www.fitflopoutlet.com]FitFlops Gogh Clogs[/url] feature three distinct densities of EVA foam in a single-fused underfoot piece, to challenge your muscles more every time you step - to deliver a workout while you walk.

人气淘

Posted on 8/22/2011 @ 7:08 PM
zhic

人气淘

Posted on 8/22/2011 @ 7:15 PM
www_rqtao_com

[url=http://www.rqtao.com]人气淘[/url]

Posted on 8/22/2011 @ 7:17 PM
www_rqtao_com

http://www.rqtao.com人气淘

Posted on 8/22/2011 @ 7:18 PM
UDSTANDER

Benny

Posted on 10/10/2011 @ 1:51 AM
This code works wonders and really helps with cutting the dependencies on configuration files.
Works well with basic http modules

pttrade999

Posted on 10/22/2011 @ 8:58 AM
more discount moncler jackets at http://www.moclercoat4u.com

tradeairmax

Posted on 11/1/2011 @ 5:38 AM
It rare to find such good collection of acoustic electronica in one album, thanks for this.

sdfhsdf

Posted on 3/13/2012 @ 2:56 AM
It rare to find such good collection of acoustic electronica in one album, thanks for this.
Post your comment and continue the discussion.