【转】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 ...
随机推荐
- [CCC 2018] 平衡树
题面在这里! 根据题目描述就可以直接模拟出一个暴力. 如果把前 n^(1/2) 的树的方案数先一遍 O(n^(3/4)) 暴力预处理出来(其实复杂度并到不了这个级别),然后把n带进来直接暴力算就行了. ...
- Java字符串池
1. String类的两个构造方法 private final char value[]; private int hash; public String() { this.value = " ...
- mysql root密码忘了怎么办?
服务器多起来,密码也就多了,多到自己记不住了,也忘记存哪里了.昨天刚刚下载了KeePass来管理密码,不过为时已晚,我已经忘记了mysql的root密码.好惨好惨,难道还要重装么.还好,有一种方法可以 ...
- 支持Tasker控制的app合集
跟各种Tasker插件打交道,原因有两点: 1.站在开发者的角度:Tasker虽为神器,也不能面面俱到,一个原因就是Android自身过于分裂化造成的,不可能兼顾全平台和机型:个人开发者精力有限,也满 ...
- NFC TI TRF7970A Breakout Board for BusPirate or other HW
http://dangerousprototypes.com/forum/viewtopic.php?f=19&t=3187 Just a news about a new Hardware ...
- The Struts dispatcher cannot be found. This is usually caused by using Struts ta
HTTP Status 500 - type Exception report message description The server encountered an internal error ...
- java.lang.RuntimeException: java.io.IOException: invalid constant type: 15
java.lang.RuntimeException: java.io.IOException: invalid constant type: 15 controller通过dubbo调用servic ...
- ExtJs4.0日期控件只显示年月按年月格式会跳月的解决办法
如果是Ext.form.panel的话,只要设置一下属性就可以.如下代码: { text : '期间', width : 80, sortable : true, dataIndex : 'accou ...
- C++ Primer 学习笔记_91_用于大型程序的工具 --命名空间
用于大型程序的工具 --命名空间 引言: 在一个给定作用域中定义的每一个名字在该作用域中必须是唯一的,对庞大.复杂的应用程序而言,这个要求可能难以满足.这样的应用程序的全局作用域中一般有很多名字定义. ...
- WPF性能调试系列 – Ants Performance Profiler
WPF性能调试系列文章: WPF页面渲染优化:Application Timeline WPF页面业务加载优化:Ants Performance Profiler WPF内存优化:Ants Memor ...