你能以编程方式定义ASP.NET配置吗?

时间:2010-08-10 05:37:24

标签: .net asp.net ihttphandler ihttpmodule

是否可以在代码中定义ASP.NET应用程序的大部分(如果不是整个)web.config?如果是这样,怎么样?你会使用IHttpModule吗?同样,你能解析所述模块中的IHttpHandler来处理所有传入的请求吗?

编辑1:最后一位是this answer to another question发起的。

编辑2:我真正想要做的是在代码中添加/删除模块和处理程序,而不是web.config。我可能至少需要在web.config中设置一个允许这个的模块。我可以注册其他模块和处理程序吗?我正在探索各种可能性。

2 个答案:

答案 0 :(得分:2)

您可以在运行时更改它。这里概述了说明和可能的陷阱:http://www.beansoftware.com/ASP.NET-Tutorials/Modify-Web.Config-Run-Time.aspx

我见过几个在安装或维护过程中修改配置的网络应用程序。 (DotNetNuke在安装过程中执行此操作,AspDotNetStorefront会在配置向导中更改多个设置。)

但请记住,每次更改web.config时,应用程序都需要重新编译,因此可能会令人烦恼。你最好在数据库中保存设置并尽可能地使用它们。更容易修改,破坏性更小。

答案 1 :(得分:1)

您可以使用PreApplicationStartupMethod在代码启动时在代码中注册HttpHandlers,而不是修改配置。示例代码(来自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();
            });
        }
    }
}

另见Phil Haack的帖子,Three Hidden Extensibility Gems in ASP.NET 4