在ASP.NET MVC中创建自定义模块

创建模块

module是实现了System.Web.IHttpModule接口的类。该接口定义了两个方法:

Init:当模块初始化时被调用,传入的参数为HttpApplication对象,用于注册请求周期事件处理方法,并初始化所需要的资源。
Dispose 当请求过程完成时调用,用于释放需显式管理的资源。
在这个程序中,我们创建一个模块,拦截beginRequest和endRequest事件,实现了输出请求到响应的执行时间

步骤:

  1. 创建TimerModule类,实现IHttpModule接口

  2. 在TimerModule,订阅需要拦截的事件

  3. 给事件添加事件处理程序

  4. 在Web.config中注册事件

模块代码:

public class TimerModule : IHttpModule
{
    private Stopwatch timer;
    public void Dispose()
    {
    }
    public void Init(HttpApplication context)
    {
        context.BeginRequest += HandleEvent;
        context.EndRequest += HandleEvent;
    }

    private void HandleEvent(object sender, EventArgs e)
    {
        HttpContext ctx = HttpContext.Current;
        if (ctx.CurrentNotification==RequestNotification.BeginRequest)
        {
            timer = Stopwatch.StartNew();
        }
        else
        {
            ctx.Response.Write(string.Format(
                "<div class='alert alert-success'>Elapsed:{0:F5} seconds</div>",
                ((float)timer.ElapsedTicks)/Stopwatch.Frequency
                ));
        }
    }
}
在Web.config中注册模块:
<system.webServer>
    <modules>
      <add name="Timer" type="Test.Infrastructure.TimerModule"/>
    </modules>
</system.webServer>
原文地址:https://www.cnblogs.com/AlexanderZhao/p/10613090.html