1. 程式人生 > >ASP.NET MVC使用AuthenticationAttribute驗證登錄

ASP.NET MVC使用AuthenticationAttribute驗證登錄

rect post方式 redirect true mvc 檢查 except () cati

首先,添加一個類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驗證登錄