Search code examples
.netasp.netihttphandlerihttpmodule

Can you programatically define ASP.NET configuration?


Is it possible to define a large portion, if not the entire, web.config of an ASP.NET application in code? If so, how? Would you use an IHttpModule? In the same vein, can you resolve an IHttpHandler within said module to handle all incoming requests?

Edit 1: The last bit was instigated by this answer to another question.

Edit 2: What I really want to do is add/remove modules and handlers in code as opposed to the web.config. I probably need to at least set a module in the web.config that would allow this. Can I then register additional modules and handlers? I'm just exploring possibilities.


Solution

  • Rather than modifying configuration, you can register HttpHandlers at application startup in code using the PreApplicationStartupMethod. Example code (from Nikhil Kothari's blog post):

    [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();
                });
            }
        }
    }
    

    Also see Phil Haack's post, Three Hidden Extensibility Gems in ASP.NET 4.