2013年12月2日 星期一

使用PreApplicationStartMethod動態註冊HTTP Module

 

Tool:Visual Studio 2013 Ultimate
OS:Windows Server 2012
.NET Framework : 4.5.1

在ASP.NET 4 版,新增一個PreApplicationStartMethodAttribute,可以指定一個方法,在Global.asax Application_Start事件之前執行,因此此方法不能夠存取到HttpApplication或HttpContext物件。

利用PreApplicationStartMethodAttribute可以在執行時期組態ASP.NET Runtime的運作,例如動態註冊Http Module。

適用於ASP.NET Web Application類型專案,不適用於ASP.NET Web Site。

以下說明使用ASP.NET Web Application專案動態註冊Http Module步驟

  • 建立ASP.NET Web Forms專案,New ASP.NET Web Application

image

  • 建立Empty- Web Forms專案

image

  • 加入一個ASP.NET Module到專案

image

  • Add Code,在每個Request結束時,自動加入Copyright說明到網頁

 

using System;
using System.Web;

namespace MyWebApp {
  public class Copyright : IHttpModule {
    /// <summary>
    /// You will need to configure this module in the Web.config file of your
    /// web and register it with IIS before being able to use it. For more information
    /// see the following link: http://go.microsoft.com/?linkid=8101007
    /// </summary>
    #region IHttpModule Members

    public void Dispose( ) {
      //clean-up code here.
    }

    public void Init( HttpApplication context ) {
      // Below is an example of how you can handle LogRequest event and provide
      // custom logging implementation for it
      context.LogRequest += new EventHandler( OnLogRequest );
      context.EndRequest += context_EndRequest;
    }

    void context_EndRequest( object sender , EventArgs e ) {
      HttpApplication application = ( HttpApplication ) sender;
      HttpContext context = application.Context;
      context.Response.Write( "<h3>Copyright by MiMiCat</h3>" );       
    }

    #endregion

    public void OnLogRequest( Object source , EventArgs e ) {
      //custom logging logic can go here
    }
  }
}

  • 使用NuGet下載

image

  • 加入PreApplicationStart類別
image
  • 加入code,動態註冊Http Module

using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyWebApp {
  public class PreApplicationStart {
    public static void Start( ) {

     DynamicModuleUtility.RegisterModule( typeof( Copyright ) );
    }
  }
}

  • 修改AssemblyInfo.cs,加入PreApplicationStartMethodAttribute:

using MyWebApp;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;

[assembly: PreApplicationStartMethod( typeof( PreApplicationStart ) , "Start" )]

  • 加入網頁測試

image

  • 直接執行網頁,便套用Http Module,加上copyright

image

  • PS: 動態註冊HTTP Module的動作不能在Applicaiton_Start事件處理,否則會得到以下錯誤:

image

沒有留言:

總網頁瀏覽量