开发者

Can you programatically define ASP.NET configuration?

开发者 https://www.devze.com 2023-01-11 09:03 出处:网络
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

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消