MVC4验证 用户登录特性 实现方法

本文介绍了一种自定义登录验证特性方法,通过继承系统提供的AuthorizeAttribute类并进行扩展,实现仅依赖Session或Cookie来判断用户的登录状态,适用于轻量级应用。

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

// 摘要:
// 表示一个特性,该特性用于限制调用方对操作方法的访问。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
但是,美中不足的是,需要微软自带的一些用户验证的东西,比如数据库,配置等等的。

常常我们只需要用SESSION或者Cookies去保存用户登录状态的时候,这岂不是杀鸡用牛刀的感觉?

那么,我们按照微软官方的这个特性,重写一个属于自己的验证特性类就行了。下面是我常用的自己写的一段代码。

复制代码
using System.Web.Mvc;
namespace System
{
///
/// 表示需要用户登录才可以使用的特性
/// 如果不需要处理用户登录,则请指定AllowAnonymousAttribute属性
///
[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文件里面加入下面几句用于配置登陆验证的一些信息:




//…省略引用
namespace MrHuo.Framework.Blog
{
[Authorization]//如果将此特性加在Controller上,那么访问这个Controller里面的方法都需要验证用户登录状态
public class UserController:Controller
{
[AllowAnonymous]//这里是一个特例,有这个特性,表示这个方法不需要验证用户登录状态
public ActionResult Index()
{
//…省略具体代码
}
//这里的方法需要验证登录状态,以下雷同
public ActionResult Create()
{
//…省略具体代码
}
}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值