MVC4验证用户登录特性实现方法
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性。
// 摘要:
// 表示一个特性,该特性用于限制调用方对操作方法的访问。
[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()
{
//...省略具体代码
}
}
}

MVC4验证用户登录特性实现方法的更多相关文章
- 【转】MVC4验证用户登录特性实现方法
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- [Asp.Net MVC4]验证用户登录实现
最近我们要做一个仿sina的微博,碰巧的是我最近在学习mvc,就想用mvc技术实现这个项目. 既然是微博,那不用想也应该知道肯定要有用户登陆,但是和常规的asp.net登陆又不一样,以下是我一下午+一 ...
- MVC4项目中验证用户登录一个特性就搞定
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- [转]MVC4项目中验证用户登录一个特性就搞定
本文转自:http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Log ...
- 转:C4项目中验证用户登录一个特性就搞定
转:C4项目中验证用户登录一个特性就搞定 在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用 ...
- easyui datagrid 禁止选中行 EF的增删改查(转载) C# 获取用户IP地址(转载) MVC EF 执行SQL语句(转载) 在EF中执行SQL语句(转载) EF中使用SQL语句或存储过程 .net MVC使用Session验证用户登录 PowerDesigner 参照完整性约束(转载)
easyui datagrid 禁止选中行 没有找到可以直接禁止的属性,但是找到两个间接禁止的方式. 方式一: //onClickRow: function (rowIndex, rowData) ...
- .net MVC使用Session验证用户登录(转载)
.net MVC使用Session验证用户登录 用最简单的Session方式记录用户登录状态 1.添加DefaultController控制器,重写OnActionExecuting方法,每次访问 ...
- 单点登录CAS使用记(三):实现自定义验证用户登录
问题: CAS自带的用户验证逻辑太过简单,如何像正常网站一样,通过验证DB中的用户数据,来验证用户以及密码的合法性呢? 方案1:CAS默认的JDBC扩展方案: CAS自带了两种简单的通过JDBC方式验 ...
- How to use the windows active directory to authenticate user via logon form 如何自定义权限系统,使用 active directory验证用户登录
https://www.devexpress.com/Support/Center/Question/Details/Q345615/how-to-use-the-windows-active-dir ...
随机推荐
- 设计模式:模版模式(Template Pattern)-转
模版模式 又叫模板方法模式,在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中.模板方法使得子类可以在不改变算法结构的情冴下,重新定义算法中的某些步骤. 我们使用冲泡咖啡和冲泡茶的例子 加工流程 ...
- 安装VVDocumenter-Xcode-master (Xcode 7.1)的过程
下载地址: http://pan.baidu.com/s/1boxvewB 1.首先下载解压压缩包打开VVDocumenter工程,编译一遍(快捷键com+B) 2.在finder里面的应用程序,找到 ...
- iOS开发之网络数据解析--中文输出
对于服务器返回的数据,解析之后直接打印,如果数据中原本有中文,可能会出现中文乱码的结果: 为了避免这个问题,可以通过类别来重写系统和打印相关的方法. 步骤: 1.新建文件名:Foundation+Lo ...
- Windows平台的Eclipse-javaEE-mars相关配置
平台:winddow10 前提: 1> 搭建好了jdk1.8.0_60环境 2> 下载放置好了apache-tomcat-8.0.24 3> 下载好了eclipse-jee-m ...
- Stronger (What Doesn't Kill You)
今天听一个歌曲,挺不错的.以前一直不知道意思.这次把歌词摘抄下来. 试听音乐: 原版MV: You know the bed feels warmer 你知道被窝里的温暖 Sleeping here ...
- 一步步学敏捷开发:6、Scrum的3种工件
Scrum的3种工件包括:Product Blacklog.Sprint Backlog.完成标准. 1.产品待办事项列表(Product Backlog) 产品Blacklog是Scrum中的核心工 ...
- 内部类--毕向东Java基础教程学习笔记
内部类的访问规则 1. 内部类可以直接访问外部类的成员,包括私有. 之所以可以直接访问外部类的成员,是因为内部类中持有外部类的引用,格式:外部类名.this 2.外部类要访问内部类,必须建立内部类对象 ...
- SQLAlchemy 做migration的时候 ValueError: too many values to unpack
我在做数据库迁移的时候,使用sqlalchemy,出现一个问题 Traceback (most recent call last): File "/Volumes/Spano/Dropbox ...
- nim2 取石头youxi
a先把石头分堆,然后bababa的顺序取石头,只能取其中一堆中的若干颗(不能不取) 这种问题先考虑 先取者的胜态问题 (1,1)先取者必败, 所以(1,x),当x>1时可以转换为(1,1)使后取 ...
- DNS报文格式
原文链接地址:http://blog.chinaunix.net/uid-24875436-id-3088461.html DNS报文格式(借个图贴过来): 说明一下:并不是所有DNS报文都有 ...