隐藏

.NET MVC5专题(IIS管道模型HttpModule事件详解)

发布:2020/10/15 20:41:51作者:管理员 来源:本站 浏览次数:914

先上个管道模型的图

在这里插入图片描述
在这里插入图片描述

首先先来个管道的类


public class CustomHttpModule : IHttpModule

{
    public void Dispose()
    {
        Console.WriteLine();
    }

    public event EventHandler CustomHttpModuleHandler;

    /// <summary>
    /// 注册动作
    /// </summary>
    /// <param name="context"></param>
    public void Init(HttpApplication application)
    {
        application.BeginRequest += (s, e) =>
          {
              this.CustomHttpModuleHandler?.Invoke(application, null);
          };
        //application.EndRequest += (s, e) =>
        //{
        //    HttpContext.Current.Response.Write("CustomHttpModule.EndRequest");
        //};
        #region 为每一个事件,都注册了一个动作,向客户端输出信息
        application.AcquireRequestState += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "AcquireRequestState        "));
        application.AuthenticateRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "AuthenticateRequest        "));
        application.AuthorizeRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "AuthorizeRequest           "));
        application.BeginRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "BeginRequest               "));
        application.Disposed += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "Disposed                   "));
        application.EndRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "EndRequest                 "));
        application.Error += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "Error                      "));
        application.LogRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "LogRequest                 "));
        application.MapRequestHandler += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "MapRequestHandler          "));
        application.PostAcquireRequestState += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostAcquireRequestState    "));
        application.PostAuthenticateRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostAuthenticateRequest    "));
        application.PostAuthorizeRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostAuthorizeRequest       "));
        application.PostLogRequest += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostLogRequest             "));
        application.PostMapRequestHandler += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostMapRequestHandler      "));
        application.PostReleaseRequestState += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostReleaseRequestState    "));
        application.PostRequestHandlerExecute += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostRequestHandlerExecute  "));
        application.PostResolveRequestCache += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostResolveRequestCache    "));
        application.PostUpdateRequestCache += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PostUpdateRequestCache     "));
        application.PreRequestHandlerExecute += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PreRequestHandlerExecute   "));
        application.PreSendRequestContent += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PreSendRequestContent      "));
        application.PreSendRequestHeaders += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "PreSendRequestHeaders      "));
        application.ReleaseRequestState += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "ReleaseRequestState        "));
        application.RequestCompleted += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "RequestCompleted           "));
        application.ResolveRequestCache += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "ResolveRequestCache        "));
        application.UpdateRequestCache += (s, e) => application.Response.Write(string.Format("<h1 style='color:#00f'>来自MyCustomModule 的处理,{0}请求到达 {1}</h1><hr>", DateTime.Now.ToString(), "UpdateRequestCache         "));
        #endregion
    }

}




<system.webServer>
    <!--集成模式使用这个-->
    <modules>
      <remove name="TelemetryCorrelationHttpModule" />

      <!--<remove name="WindowsAuthentication"/>
      <remove name="FormsAuthentication"/>
      <remove name="PassportAuthentication"/>-->
      
      <add name="CustomHttpModule" type="MVC5.Utility.Pipeline.CustomHttpModule,MVC5"/>

      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>



对于modul中注册的自定义事件需要在全局文件中执行代码如下

public class MvcApplication : System.Web.HttpApplication
{
    private Logger logger = new Logger(typeof(MvcApplication));
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();//注册区域
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//注册全局的Filter
        RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由
        BundleConfig.RegisterBundles(BundleTable.Bundles);//合并压缩 ,打包工具 Combres
        ControllerBuilder.Current.SetControllerFactory(new ElevenControllerFactory());

        this.logger.Info("网站启动了。。。");
    }
    /// <summary>
    /// 全局式的异常处理,可以抓住漏网之鱼
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception excetion = Server.GetLastError();
        this.logger.Error($"{base.Context.Request.Url.AbsoluteUri}出现异常");
        Response.Write("System is Error....");
        Server.ClearError();

        //Response.Redirect
        //base.Context.RewritePath("/Home/Error?msg=")
    }

//这个就算modul里注册事件的执行方法
    protected void CustomHttpModuleEleven_CustomHttpModuleHandler(object sender, EventArgs e)
    {
        this.logger.Info("this is CustomHttpModuleEleven_CustomHttpModuleHandler");
    }


    /// <summary>
    /// 会在系统新增一个session时候触发
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Session_Start(object sender, EventArgs e)
    {
        HttpContext.Current.Application.Lock();
        object oValue = HttpContext.Current.Application.Get("TotalCount");
        if (oValue == null)
        {
            HttpContext.Current.Application.Add("TotalCount", 1);
        }
        else
        {
            HttpContext.Current.Application.Add("TotalCount", (int)oValue + 1);
        }
        HttpContext.Current.Application.UnLock();
        this.logger.Debug("这里执行了Session_Start");
    }

    /// <summary>
    /// 系统释放一个session的时候
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Session_End(object sender, EventArgs e)
    {
        this.logger.Debug("这里执行了Session_End");
    }

}