views:

81

answers:

2

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.

+3  A: 

You can change it at run-time. Instructions and possible pitfalls are outlined here: http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

I've seen several web apps that modify the configuration during an Installation or Maintenance process. (DotNetNuke does it during install, and AspDotNetStorefront changes several settings as part of the configuration wizard.)

But remember that every time you change the web.config, the app needs to recompile, so it can be an annoyance. You'd be better off saving settings in a database and using those where you can. Easier to modify and less disruptive.

David Stratton
Thanks for your response, David. It may be that it addresses what I'm trying to find out. I've updated my question to be more specific to my intent.
Ryan Riley
+2  A: 

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.

Jon Galloway