【转】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 ...
随机推荐
- 【贪心】BZOJ3668-[NOI2014]起床困难综合症
[题目大意] 给定n次操作(与,或,异或),在0~m中选择一个数,使这个数经过n次操作后得到的值最大. [思路] 水题orz 枚举这个数每一位的取值是0还是1,然后根据它经过n次操作后的结果判断: ( ...
- thread_local变量(转)
转自:https://www.cnblogs.com/pop-lar/p/5123014.html thread_local变量是C++11新引入的一种存储类型.它会影响变量的存储周期(Storage ...
- [转]使用popBackStack()清除Fragment
Clear back stack using fragments up vote88down votefavorite 27 I ported my Android app to honeycomb ...
- UESTC 2015dp专题 F 邱老师看电影 概率dp
邱老师看电影 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/contest/show/65 Descr ...
- Codeforces Round #304 (Div. 2) Break the Chocolate 水题
Break the Chocolate Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/546/ ...
- CC1150 针对低功耗无线应用设计的高度集成多通道射频发送器
Low Power Sub-1 GHz RF Transmitter 单片低成本低能耗 RF 发送芯片 应用 极低功率 UHF 无线发送器 315/433/868 和 915MHz ISM/SRD 波 ...
- 发布一个C++版本的ORM库SmartDB
先简单说说ORM的优点: 提高开发效率,减少重复劳动,只和业务实体打交道,由业务实体自动生成sql语句,不用手写sql语句. 简单易用, 可维护性好. 隔离数据源,使得我们更换数据源时不用修改代码. ...
- Java Collection 简介
转自:http://skyuck.iteye.com/blog/526358 在 Java2中,有一套设计优良的接口和类组成了Java集合框架Collection,使程序员操作成批的数据或对象元素极为 ...
- SQL中关于where后面不能放聚合函数(如sum等)的解决办法
我们在编写较为复杂的SQL语句的时候,常常会遇到需要将sum()放到where后面作为条件查询,事实证明这样是无法执行的,执行会报[此处不允许使用分组函数]异常. 那么如何解决呢,使用HAVING关键 ...
- ABC定制视图导航控制器
ABCustomUINavigationController ABC定制视图导航控制器 Subclass of UINavigationController for overwriting ...