在开发过程当中,须要用户登录才能访问指定的页面这种功能,微软已经提供了[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() { //...省略具体代码 } } }
博客园的大牛们的支持,是我一直写下去的动力。