转:C4项目中验证用户登录一个特性就搞定

转:C4项目中验证用户登录一个特性就搞定

 

在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性。

    // 摘要:
    //     表示一个特性,该特性用于限制调用方对操作方法的访问。
    [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();               
}           
}       
}       

privateString _AuthSaveType =String.Empty;       
/// <summary>       
/// 获取或者设置一个值,该值表示用来保存登陆信息的方式       
/// <para>如果web.config中未定义AuthSaveType的值,则默认为Session保存</para>       
/// </summary>       
publicStringAuthSaveType       
{           
get{return _AuthSaveType.Trim().ToUpper();}           
set           
{               
if(String.IsNullOrEmpty(value))               
{                   
thrownewArgumentNullException("用于保存登陆信息的方式不能为空,只能为【Cookie】或者【Session】!");               
}               
else               
{                    _AuthSaveType
= value.Trim();               
}           
}       
}       

/// <summary>       
/// 处理用户登录       
/// </summary>       
/// <param name="filterContext"></param>       
publicvoidOnAuthorization(AuthorizationContext filterContext)       
{           
if(filterContext.HttpContext==null)           
{               
thrownewException("此特性只适合于Web应用程序使用!");           
}           
else           
{               
switch(AuthSaveType)               
{                   
case"SESSION":                       
if(filterContext.HttpContext.Session==null)                       
{                           
thrownewException("服务器Session不可用!");                       
}                       
elseif(!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true)
&&!filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute),true))                       
{                           
if(filterContext.HttpContext.Session[_AuthSaveKey]==null)                           
{                                filterContext
.Result=newRedirectResult(_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=newRedirectResult(_AuthUrl);                           
}                       
}                       
break;                   
default:                       
thrownewArgumentNullException("用于保存登陆信息的方式不能为空,只能为【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()
        {
            //...省略具体代码
        }
    }
}

 

posted on 2014-06-30 19:21  Whyisalive  阅读(392)  评论(0编辑  收藏  举报