您可以在应用程序启动时使用 PreApplicationStartupMethod 在代码中注册 HttpHandler,而不是修改配置。示例代码(来自Nikhil Kothari 的博客文章):
[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 的帖子,ASP.NET 4 中的三个隐藏的可扩展性宝石。