使用ActionFilterAttribute實現MVC後臺受權

受權就是咱們在用戶未登陸的狀況下不容許訪問一些頁面,只有登陸後才能進行訪問一些頁面。mvc

在mvc中咱們能夠使用ActionFilterAttribute來進行受權驗證來阻止一些未經受權的直接訪問的頁面。ide

首先再咱們的項目中根目錄中建立一個文件夾命名爲Filter,在該文件夾內建立一個普通的類,注意:類名必須以 "Attribute" 結尾。spa

下圖代碼爲受權驗證類:code

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace MVC_CRUD.filters
 8 {
 9     public class MyAuthorizeFilterAttribute : ActionFilterAttribute//必須繼承於ActionFilterAttribute
10     {
11         public override void OnActionExecuted(ActionExecutedContext filterContext)//重寫OnActionExecuted,
12         {
13             base.OnActionExecuted(filterContext);
14             HttpContextBase http = filterContext.HttpContext;
15             if (http.Request.Cookies["adminName"]==null)//判斷是否有cookise(用戶登陸存入的cookise)
16             {
17                 http.Response.Redirect("http://localhost:1299/Home/login");//要跳轉的頁面(通常都是跳轉至登陸頁)
18             }
19         }
20     }
21 }

寫好受權後,咱們要在須要受權的控制器中加上咱們的特性,好比我要在Index上驗證未登陸用戶不可訪問,能夠在它的Action上方加上[MyAuthorizeFilter]blog

注意咱們要在using 引用咱們的文件,不然會找不到。繼承

 

 若是整個控制器的Action中須要受權驗證,那麼能夠在控制器類上方加上[MyAuthorizeFilter]。io

這樣能夠達到當咱們運行一個受權的頁面在未登陸的狀況下自動跳轉到登陸頁面。class

相關文章
相關標籤/搜索