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

// 摘要:
// 表示一个特性,该特性用于限制调用方对操作方法的访问。
[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验证用户登录特性实现方法的更多相关文章

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

    在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...

  2. [Asp.Net MVC4]验证用户登录实现

    最近我们要做一个仿sina的微博,碰巧的是我最近在学习mvc,就想用mvc技术实现这个项目. 既然是微博,那不用想也应该知道肯定要有用户登陆,但是和常规的asp.net登陆又不一样,以下是我一下午+一 ...

  3. MVC4项目中验证用户登录一个特性就搞定

    在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...

  4. [转]MVC4项目中验证用户登录一个特性就搞定

    本文转自:http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Log ...

  5. 转:C4项目中验证用户登录一个特性就搞定

    转:C4项目中验证用户登录一个特性就搞定   在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性.     // 摘要:    //     表示一个特性,该特性用于限制调用 ...

  6. easyui datagrid 禁止选中行 EF的增删改查(转载) C# 获取用户IP地址(转载) MVC EF 执行SQL语句(转载) 在EF中执行SQL语句(转载) EF中使用SQL语句或存储过程 .net MVC使用Session验证用户登录 PowerDesigner 参照完整性约束(转载)

    easyui datagrid 禁止选中行   没有找到可以直接禁止的属性,但是找到两个间接禁止的方式. 方式一: //onClickRow: function (rowIndex, rowData) ...

  7. .net MVC使用Session验证用户登录(转载)

    .net MVC使用Session验证用户登录   用最简单的Session方式记录用户登录状态 1.添加DefaultController控制器,重写OnActionExecuting方法,每次访问 ...

  8. 单点登录CAS使用记(三):实现自定义验证用户登录

    问题: CAS自带的用户验证逻辑太过简单,如何像正常网站一样,通过验证DB中的用户数据,来验证用户以及密码的合法性呢? 方案1:CAS默认的JDBC扩展方案: CAS自带了两种简单的通过JDBC方式验 ...

  9. 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 ...

随机推荐

  1. 探究react-native 源码的图片缓存

    先看js端图片使用的三种方式,依次排序1.2.3 <Image source={{uri:url}} style={{width:200,height:200}}/> 1. 加载远程图片 ...

  2. webstrom内置压缩工具YUI-compressor详解

    压缩工具层次不穷,各有优点,选择适合的压缩工具为将来做项目开发使用是一件很重要的事情!!在这介绍YUI-compressor 英文官网:http://yui.github.io/yuicompress ...

  3. IntelliJ IDEA导出设置

    导出: [File]->[Export Settings] 导入: [File]->[Import Settings]

  4. iOS开发中虚拟键盘相关的坑

    初学者在学习iOS开发时,遇到在一个textField中输入完内容后却发现虚拟键盘无法隐藏起来而不知所措的情况的人一定不占少数吧.这篇文章就说说我遇到的和虚拟键盘有关的三个问题及解决对策. 在模拟器测 ...

  5. MC34063组成DC-DC电路

    +VO的输出电压峰值可达2倍V_IN,-VO的输出电压可达-V_IN. 需要注意的是,3路的峰值电路不能超过1.5A,同时两路附加电源的输出功率和必须小于V_IN·I·(1-D), 其中I为主输出的电 ...

  6. sqlserver获取所有表和表字段

    SELECT [number]=a.colorder, [column] =a.name, [datatype]=b.name, [length]=COLUMNPROPERTY(a.id,a.name ...

  7. source insight完全卸载

    由于不知名原因 source insight崩溃了,使用自带的卸载,完成之后重新安装软件注册还是出问题.在网上搜索资料发现就是删除注册表中的内容. 由于列出的删除项目不完全,导致还是出问题. 最后删除 ...

  8. MySQL在windows系统的安装

    原文:https://blog.csdn.net/wokaowokaowokao12345/article/details/76736152 MySQL在windows系统的安装 原创 2017年08 ...

  9. 微信公众平台——获取access_token、expires_in

    微信公众平台——获取access_token.expires_in 在微信公众平台接口开发中,Access Token占据着重要地位,它相当于进入各种接口的邀请,拿到这个钥匙才拥有调用其他各种特殊接口 ...

  10. Go:《Go语言 云动力》

    背景 中秋快速的读了一遍<Go语言 云动力>,对Go有一下几点感觉: 在静态类型和动态类型之间取得了非常好的平衡,隐式接口实现会被后续的语言借鉴(希望C#能借鉴一下). 缺乏异常处理机制, ...