ASP.NET MVC使用AuthenticationAttribute驗證登入

來源:互聯網
上載者:User

標籤:void   ==   get   filter   namespace   action   anon   asp   cep   

首先,添加一個類AuthenticationAttribute,該類繼承AuthorizeAttribute,如下:

using System.Web;using System.Web.Mvc;namespace Zhong.Web{    public class AuthenticationAttribute : AuthorizeAttribute    {        public override void OnAuthorization(AuthorizationContext filterContext)        {            //base.OnAuthorization(filterContext);            //如果控制器沒有加AllowAnonymous特性或者Action沒有加AllowAnonymous特性才檢查            if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true))            {                //此處寫判斷是否登入的邏輯代碼                //這裡使用cookie來判斷是否登入,為了簡單說明特性的使用方式,cookie記錄的是使用者名稱和純文字密碼(實際當中需要經過諸如加密等處理)                HttpCookie cookie = filterContext.HttpContext.Request.Cookies["Member"];                if (!(cookie!=null && cookie.Values["name"] == "test" && cookie.Values["pass"] == "123"))                {                    filterContext.Result = new RedirectResult("/Member/Login");                }            }        }    }}
View Code

在MemberControll中加上特性Authentication,Member控制器下有三個Action方法,一個是首頁Index,一個是登入頁Login,一個是處理Post方式的登入頁Login,Index對應的視圖代碼如下:

@{    ViewBag.Title = "Index";}<h2>這是測試人員中樞</h2>

Login對應的視圖代碼如下:

@{    ViewBag.Title = "Login";}<h2>會員登入</h2>@using (Html.BeginForm()){    <label>使用者名稱:</label><input type="text" name="name" /><br />    <label>密碼:</label><input type="password" name="password" /><br />    <input type="submit" value="登入" /> }

 

當沒有登入直接存取Member/Index時,會跳轉到Login。當輸入正確的使用者名稱密碼登入時,會跳轉到Index頁面。

 

 

 

 

 

完整的MemberController代碼如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Zhong.Web.Controllers{    [Authentication]    public class MemberController : Controller    {        // GET: Member        public ActionResult Index()        {            return View();        }        [AllowAnonymous]        public ActionResult Login()        {            return View();        }        [AllowAnonymous]        [HttpPost]        public ActionResult Login(string name,string password)        {            //這裡為了簡單示範一下登入的判斷,主要是驗證AuthenticationAttribute的作用,實際的運用中可能要查詢資料庫、            //密碼判斷需要加密處理等            if (name == "test" && password == "123")            {                HttpCookie cookie = new HttpCookie("Member");                cookie.Values["name"] = "test";                cookie.Values["pass"] = "123";                Response.Cookies.Add(cookie);                return RedirectToAction("Index");            }            return View();        }    }}
View Code

特別說明:由於控制器使用了Authentication特性,所以請求其下的所有Action都要先通過授權/登入 驗證,Login是登入頁面,訪問這個頁面一般是沒有登入的狀態,所以需要允許匿名訪問,於是加了[AllowAnonymous]

 

 

 上面的AuthorizationAttribute的另一種寫法是繼承FilterAttribute 並實現介面IAuthorizationFilter,方式與系統的AuthorizeAttribute類似,

 

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Zhong.Web{    public class TestAttribute : FilterAttribute, IAuthorizationFilter    {        public void OnAuthorization(AuthorizationContext filterContext)        {            //throw new NotImplementedException();            //TODO: 此處寫需要實現登入驗證的代碼        }    }}
View Code

 

ASP.NET MVC使用AuthenticationAttribute驗證登入

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.