本文轉自:http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Login
在開發過程中,需要用戶登陸才能訪問指定的頁面這種功能,微軟已經提供了這個特性。 // 摘要: // 表示一個特性,該特性用於限制調用方對操作方法的訪問。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter 但是,美中不足的是,需要微軟自帶的一些用戶驗證的東西,比如數據庫,配置等等的。 常常我們只需要用SESSION或者Cookies去保存用戶登錄狀態的時候,這豈不是殺雞用牛刀的感覺? 那么,我們按照微軟官方的這個特性,重寫一個屬於自己的驗證特性類就行了。下面是我常用的自己寫的一段代碼,希望大家用得開心,如果有異議可以自己修改,代碼無版權,哈哈,我們只為共享。下面也提供了一個可以直接引用的DLL,需要.NET 4.0 Framework的支持。 下載地址: 點擊這里下載 代碼: using System.Web.Mvc; namespace System { /// <summary> /// 表示需要用戶登錄才可以使用的特性 /// <para>如果不需要處理用戶登錄,則請指定AllowAnonymousAttribute屬性</para> /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)] public class AuthorizationAttribute : FilterAttribute, IAuthorizationFilter { /// <summary> /// 默認構造函數 /// </summary> public AuthorizationAttribute() { String authUrl = System.Configuration.ConfigurationManager.AppSettings["AuthUrl"]; String saveKey = System.Configuration.ConfigurationManager.AppSettings["AuthSaveKey"]; String saveType = System.Configuration.ConfigurationManager.AppSettings["AuthSaveType"]; if (String.IsNullOrEmpty(authUrl)) { this._AuthUrl = "/User/Login"; } else { this._AuthUrl = authUrl; } if (String.IsNullOrEmpty(saveKey)) { this._AuthSaveKey = "LoginedUser"; } else { this._AuthSaveKey = saveKey; } if (String.IsNullOrEmpty(saveType)) { this._AuthSaveType = "Session"; } else { this._AuthSaveType = saveType; } } /// <summary> /// 構造函數重載 /// </summary> /// <param name="loginUrl">表示沒有登錄跳轉的登錄地址</param> public AuthorizationAttribute(String authUrl) : this() { this._AuthUrl = authUrl; } /// <summary> /// 構造函數重載 /// </summary> /// <param name="loginUrl">表示沒有登錄跳轉的登錄地址</param> /// <param name="saveKey">表示登錄用來保存登陸信息的鍵名</param> public AuthorizationAttribute(String authUrl, String saveKey) : this(authUrl) { this._AuthSaveKey = saveKey; this._AuthSaveType = "Session"; } /// <summary> /// 構造函數重載 /// </summary> /// <param name="authUrl">表示沒有登錄跳轉的登錄地址</param> /// <param name="saveKey">表示登錄用來保存登陸信息的鍵名</param> /// <param name="saveType">表示登錄用來保存登陸信息的方式</param> public AuthorizationAttribute(String authUrl, String saveKey, String saveType) : this(authUrl, saveKey) { this._AuthSaveType = saveType; } private String _AuthUrl = String.Empty; /// <summary> /// 獲取或者設置一個值,改值表示登錄地址 /// <para>如果web.config中未定義AuthUrl的值,則默認為/User/Login</para> /// </summary> public String AuthUrl { get { return _AuthUrl.Trim(); } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於驗證用戶登錄信息的登錄地址不能為空!"); } else { _AuthUrl = value.Trim(); } } } private String _AuthSaveKey = String.Empty; /// <summary> /// 獲取或者設置一個值,改值表示登錄用來保存登陸信息的鍵名 /// <para>如果web.config中未定義AuthSaveKey的值,則默認為LoginedUser</para> /// </summary> public String AuthSaveKey { get { return _AuthSaveKey.Trim(); } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於保存登陸信息的鍵名不能為空!"); } else { this._AuthSaveKey = value.Trim(); } } } private String _AuthSaveType = String.Empty; /// <summary> /// 獲取或者設置一個值,該值表示用來保存登陸信息的方式 /// <para>如果web.config中未定義AuthSaveType的值,則默認為Session保存</para> /// </summary> public String AuthSaveType { get { return _AuthSaveType.Trim().ToUpper(); } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於保存登陸信息的方式不能為空,只能為【Cookie】或者【Session】!"); } else { _AuthSaveType = value.Trim(); } } } /// <summary> /// 處理用戶登錄 /// </summary> /// <param name="filterContext"></param> public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext == null) { throw new Exception("此特性只適合於Web應用程序使用!"); } else { switch (AuthSaveType) { case "SESSION": if (filterContext.HttpContext.Session == null) { throw new Exception("服務器Session不可用!"); } else if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { if (filterContext.HttpContext.Session[_AuthSaveKey] == null) { filterContext.Result = new RedirectResult(_AuthUrl); } } break; case "COOKIE": if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { if (filterContext.HttpContext.Request.Cookies[_AuthSaveKey] == null) { filterContext.Result = new RedirectResult(_AuthUrl); } } break; default: throw new ArgumentNullException("用於保存登陸信息的方式不能為空,只能為【Cookie】或者【Session】!"); } } } } } 然后在Web.Config文件里面加入下面幾句用於配置登陸驗證的一些信息: <appSettings> <add key="AuthUrl" value="/User/Login" /> <add key="AuthSaveKey" value="LoginedUser" /> <add key="AuthSaveType" value="Session" /> </appSettings> 使用實例: //...省略引用 namespace MrHuo.Framework.Blog { [Authorization]//如果將此特性加在Controller上,那么訪問這個Controller里面的方法都需要驗證用戶登錄狀態 public class UserController:Controller { [AllowAnonymous]//這里是一個特例,有這個特性,表示這個方法不需要驗證用戶登錄狀態 public ActionResult Index() { //...省略具體代碼 } //這里的方法需要驗證登錄狀態,以下雷同 public ActionResult Create() { //...省略具體代碼 } } }