ASP.Net MVC Filter驗證使用者登入

來源:互聯網
上載者:User

標籤:style   四種   標籤   response   儲存   過濾器   sharp   sum   實踐   

一、Filter是什麼

    ASP.NetMVC模式內建的過濾器Filter,是一種聲明式編程方式,支援四種過濾器類型,各自是:Authorization(授權),Action(行為),Result(結果)和Exception(異常)。

過濾器類型

介面

描寫敘述

Authorization

IAuthorizationFilter

此類型(或過濾器)用於限制進入控制器或控制器的某個行為方法

Exception

IExceptionFilter

用於指定一個行為,這個被指定的行為處理某個行為方法或某個控制器裡面拋出的異常

Action

IActionFilter

用於進入行為之前或之後的處理

Result

IResultFilter

用於返回結果的之前或之後的處理

 

    可是預設實現它們的過濾器僅僅有三種,各自是ActionFilter(方法),Authorize(授權),HandleError(錯誤處理)。各種資訊例如以下表所看到的:


過濾器

類名

實現介面

描寫敘述

ActionFilter

AuthorizeAttribute

IAuthorizationFilter

此類型(或過濾器)用於限制進入控制器或控制器的某個行為方法

HandleError

HandleErrorAttribute

IExceptionFilter

用於指定一個行為,這個被指定的行為處理某個行為方法或某個控制器裡面拋出的異常

自己定義

ActionFilterAttribute

IActionFilter和IResultFilter

方法運行前/後的處理。                             返回結果的之前或之後的處理。


    第三種自己定義的過濾器,一定要繼承ActionFilterAttribute。

它是ASP.NETMVCFramework提供的基類ActionFilterAttribute。這個類實現了IActionFilter和IResultFilter介面。ActionFilterAttribute有下面幾個方法能夠重寫:

  • OnActionExecuting

    在controller action運行之前調用

    OnActionExecuted

    在controller action運行之後調用

    OnResultExecuting

    在controller action result運行之前調用

    OnResultExecuted

    在controller action result運行之後調用


    實現每一個頁面都驗證cookie中是否存實使用者資訊。到期使用者資訊就失效,跳轉登入頁面。

總體思路是這種:先在登入Controller中把頁面傳來的User資訊儲存到cookie中,設定cookie失效時間。每一個Controller中的方法運行都會先運行Filter。查看cookie中是否存實使用者資訊。

 

二、實踐   

    首先要把username資訊儲存到cookie中。在登入的Controller中建立cookie。cookie是一種鍵值對模式(key, value)。

#region 將username存到cookie中        /// <summary>        /// 儲存Cookie        /// </summary>        /// <returns></returns>        public void CreateCookie()   //此Action自己主動往cookie裡寫入登入資訊        {            HttpCookie UserName = new HttpCookie("name");            UserName.Value = Request["userName"];            System.Web.HttpContext.Current.Response.SetCookie(UserName);            //cookie儲存時間            UserName.Expires = DateTime.Now.AddHours(10);        }        #endregion

    其次,在Filter中建立自己定義的的LoginFilter,檢查cookie是否實使用者資訊:

    //類和方法都使用時,加上這個特性,此時都其作用,不加。僅僅方法起作用    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]    public class LoginFilter:ActionFilterAttribute    {        /// <summary>        /// OnActionExecuting是Action運行前的操作        /// </summary>        /// <param name="filterContext"></param>        public override void OnActionExecuting(ActionExecutingContext filterContext)        {            //推斷Cookieusernamepassword是否存在            HttpCookie cookieName = System.Web.HttpContext.Current.Request.Cookies.Get("name");            if ( cookieName == null)            {                filterContext.Result = new RedirectResult("/Login/Index");            }        }    }

最後,要在每一個Controller中打下自己定義的Filter的標籤

<span style="font-size:18px;">    [LoginFilter]    public class HomeController : Controller    {        public ActionResult Index()        {            ViewBag.Message = "歡迎使用 ASP.NET MVC!";            return View();        }       </span>
        在Controller上打了標籤,下邊的全部方法運行前都會先運行Filter,實現了過濾。可依據自己的業務。調整標籤;或是使用全域的Global。

        這次的Filter學習,暴露了我的一個缺點,調試bug,遇到紅色波浪線就ctrl + z 撤銷,而不是去認真的看問題,解決這個問題。自檢!


ASP.Net MVC Filter驗證使用者登入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.