在開發過程中,需要用戶登陸才能訪問指定的頁面這種功能,微軟已經提供了這個特性。
// 摘要: // 表示一個特性,該特性用於限制調用方對操作方法的訪問。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
但是,美中不足的是,需要微軟自帶的一些用戶驗證的東西,比如數據庫,配置等等的。
常常我們只需要用SESSION或者Cookies去保存用戶登錄狀態的時候,這豈不是殺雞用牛刀的感覺?
那么,我們按照微軟官方的這個特性,重寫一個屬於自己的驗證特性類就行了。下面是我常用的自己寫的一段代碼。
using System.Web.Mvc; namespace System { /// <summary> /// 表示需要用戶登錄才可以使用的特性 /// 如果不需要處理用戶登錄,則請指定AllowAnonymousAttribute屬性 /// </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 = "/waste/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="authUrl">表示沒有登錄跳轉的登錄地址</param> public AuthorizationAttribute(String authUrl): this() { this._AuthUrl = authUrl; } /// <summary> /// 構造函數重載 /// </summary> /// <param name="authUrl">表示沒有登錄跳轉的登錄地址</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; } /// <summary> /// 獲取或者設置一個值,該值表示登錄地址 /// 如果web.config中末定義AuthUrl的值,則默認為:/waste/user/login /// </summary> private String _AuthUrl = String.Empty; public String AuthUrl { get { return _AuthUrl.Trim(); } set { if (String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於驗證用戶登錄信息的登錄地址不能為空!"); } else { _AuthUrl = value.Trim(); } } } /// <summary> /// 獲取或者設置一個值,該值表示登錄用來保存登陸信息的鍵名 /// 如果web.config中末定義AuthSaveKey的值,則默認為LoginedUser /// </summary> private String _AuthSaveKey = String.Empty; public String AuthSaveKey { get { return _AuthSaveKey.Trim(); } set { if(String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於保存登陸信息的鍵名不能為空!"); } else { this._AuthSaveKey = value.Trim(); } } } /// <summary> /// 獲取或者設置一個值,該值用來保存登錄信息的方式 /// 如果web.config中末定義AuthSaveType的值,則默認為Session保存 /// </summary> private String _AuthSaveType = String.Empty; public String AuthSaveType { get { return _AuthSaveType.Trim().ToUpper(); } set { if(String.IsNullOrEmpty(value)) { throw new ArgumentNullException("用於保存登陸信息的方式不能為空,只能為【Cookie】或者【Session】!"); } else { _AuthSaveType = value.Trim(); } } } 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() { //...省略具體代碼 } } }
