1. 程式人生 > >自定義HttpModule實現某些功能的例子

自定義HttpModule實現某些功能的例子

        在執行使用者請求的時候可能會有一些特殊的要求例如驗證使用者是否登入,URL重寫等。這些問題需要在執行常規程式碼之前執行,這裡就用到了自定義HttpModules。具體的使用方法如下:

       自定義一個類  :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Project.Common
{
    //過濾器。
   public class CheckSessionModule:IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            //URL重寫。
           context.AcquireRequestState+=context_AcquireRequestState;
        }
        public void context_AcquireRequestState(object sender, EventArgs e)
        {
            //判斷Session是否有值.
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            string url = context.Request.Url.ToString();//獲取使用者請求的URL地址.
            if (url.Contains("AdminManger"))
            {
                if (context.Session["userInfo"] == null)
                {
                    context.Response.Redirect("要跳轉的頁面");
                }
            }
        }
    }
}

 在WebConfig檔案中對自定義的HttpModule類進行註冊

<system.webServer>
    <modules>
      <add name="CheckSessionModule" type="Project.Common.CheckSessionModule"/>
    </modules>
  </system.webServer>

這樣  在HttpApplication 呼叫InitModules方法的時候就會註冊我們自己定義的事件  實現相應的功能