MVC利用過濾器實現登錄驗證

mvc的知識過濾器可以自己查找,這裡只是簡單demo。

新建項目,添加引用首先新建4.5框架的web應用空程序。創建好後,進入包控制檯,執行命令來添加兩個關鍵引用:

install-package microsoft.aspnet.mvc.zh-hansinstall-package microsoft.aspnet.Web.Optimization.zh-hans


項目結構如圖


MVC利用過濾器實現登錄驗證

在global.asax文件種配置一個路由用於請求。

<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Mvc;
using System.Web.Routing;

namespace LoginAttributeDemo
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.MapRoute(name:"default",url:"{controller}/{action}");
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}/<code>

創建自定義校驗過濾器LoginCheckFilter

<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LoginAttributeDemo
{
    public class LoginCheckFilter : FilterAttribute,IAuthorizationFilter
    {
        public bool IsCheck { get; set; }

        public LoginCheckFilter(bool ischeck=false)
        {
            IsCheck = ischeck;
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (IsCheck)
            {
                var cookie = HttpContext.Current.Request.Cookies["user"];
                if(cookie==null)
                {
                    HttpContext.Current.Response.Write("失敗");
                    // 結束當前請求
                    HttpContext.Current.Response.End();
                }
            }
        }
    }
}/<code>

主要就是繼承了一個類和接口,IAuthorizationFilter的方法會在進入控制器或其方法時執行,這樣就達到了過濾器的作用。
創建控制器

<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LoginAttributeDemo
{
    public class UserController:Controller
    {
        [LoginCheckFilter(true)]
        public ActionResult Index()
        {
            return Content("成功");
        }
    }
}/<code>

當LoginCheckFilter傳入為true時才進行校驗。允許,瀏覽器請求user/index,發現成功被攔截了。


MVC利用過濾器實現登錄驗證

刷新頁面,因為有了cookie通過了校驗,成功訪問了action


MVC利用過濾器實現登錄驗證


分享到:


相關文章: