zoukankan      html  css  js  c++  java
  • MVC4 验证用户登录一个特性搞定

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

        // 摘要:
        //     表示一个特性,该特性用于限制调用方对操作方法的访问。

       
     [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>

    使用实例:

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

    出自: http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Login
    (只为方便,望MrHuo博主理解!)
     
  • 相关阅读:
    moment获取天的23时59分59秒可以用moment().endOf(String),以及获取天的0时0分0秒可以用moment().startOf('day')
    vue 去除输入框首位的空格
    管道
    事件广播
    iview在子组件中调用父组件的方法
    ZOJ 3430 Detect the Virus(AC自动机)
    HDU 3065 病毒侵袭持续中(AC自动机)
    HDU 2896 病毒侵袭(AC自动机)
    HDU 2222 Keywords Search(AC自动机)
    shell常用命令
  • 原文地址:https://www.cnblogs.com/oldcell/p/3897279.html
Copyright © 2011-2022 走看看