在開發過程當中,須要用戶登錄才能訪問指定的頁面這種功能,微軟已經提供了[AuthorizeAttribute]這個特性:web
// 摘要: // 表示一個特性,該特性用於限制調用方對操做方法的訪問。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
可是,美中不足的是,須要微軟自帶的一些用戶驗證的東西,好比數據庫,配置等等的。數據庫
經常咱們只須要用SESSION或者Cookies去保存用戶登陸狀態的時候,這豈不是殺雞用牛刀的感受?服務器
那麼,咱們按照微軟官方的這個特性,重寫一個屬於本身的驗證特性類就好了。下面是我經常使用的本身寫的一段代碼,但願你們用得開心,若是有異議能夠本身修改,代碼無版權,哈哈,咱們只爲共享。下面也提供了一個能夠直接引用的DLL,須要.NET 4.0 Framework的支持。app
下載地址:函數
點擊這裏下載this
廢話不說了,上代碼:spa
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】!"); } } } } }
使用方法:code
一、引用DLL,下載地址在上邊。blog
二、而後在Web.Config文件裏面加入下面幾句用於配置登錄驗證的一些信息:ip
<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() { //...省略具體代碼 } } }
博客園的大牛們的支持,是我一直寫下去的動力。