惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
Jina AI
Jina AI
量子位
博客园 - 叶小钗
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
博客园 - 聂微东
美团技术团队
Last Week in AI
Last Week in AI
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog

博客园 - Sphix

根据银行卡获取银行卡开户银行和类型 HTTP could not register URL http://+:8000/testservice/. Your... 一些必不可少的Sublime Text 2插件 C# CultureInfo列表 解决"There is already an open DataReader associated with this Command which must be closed first." exception in EF 中 C#正则表达式整理备忘 Lucene.net 开发记录 ASP.net 视频上传转换flv并且抓取第一帧生成图片源码 揭秘全球最大网站Facebook背后的那些软件 asp.net网站管理工具 的 地址(Web Site Administration Tool ) Sql Server 2008 Full-text search Error: Word breaking timed out for the full-text query string. Associations in EF Code First CTP5: Part 1 – Complex Types C# Enum 类型的本地化 wordpress 文章缩略图功能 简单实际的方式分隔Admin 区域 EF4 中Self-track entity 错误用于单web开发中要注意的地方 C#验证文件类型 Asp.net文件下载 SQLite 资源汇总
在Asp.net 4.0 中动态注册HttpModule
Sphix · 2011-08-01 · via 博客园 - Sphix

动态注册HttpModule使我们使用自定义的HttpModel时候不在需在配置文件里配置HttpModel,避免过多的配置出错情况。让我们来看看如何实现动态注册HttpModule.

First,我们实现自定义的HttpModel

public class CustomModule : IHttpModule
    {
        
public void Dispose()
        {
            
//nothing to do here
        }public void Init(HttpApplication context)
        {
            context.BeginRequest 
+= (sender, e) => ProcessCookie((HttpApplication)sender);
        }
    }
}
  

Second,建立一个静态类,并命名为PreApplicationStartCode,并增加一个静态方法PreStart()

    public class PreApplicationStartCode
    {
        
private static bool _isStarting;public static void PreStart()
        {
            
if (!_isStarting)
            {
                _isStarting 
= true;//注意这里的动态注册,此静态方法在Microsoft.Web.Infrastructure.DynamicModuleHelper
                DynamicModuleUtility.RegisterModule(typeof(CustomModule));
            }
        }
    }

Note.这里的类名官方里面建议用PreApplicationStartCode,我没测试过,大家可以测试下用其他类名

Three,在Properties/AssemblyInfo.cs里面注册

[assembly: PreApplicationStartMethod(typeof(MyTest.PreApplicationStartCode), "PreStart")]

通过这三步,你的HttpModule就不在需要为每个应用程序去配置了,这种方式比较适合开发组件DLL的时候,需要注册HttpModule的情况,微软的Asp.net MVC3里都是使用的动态HttpModule,有兴趣可以去看源码。