转:C4项目中验证用户登录一个特性就搞定
转:C4项目中验证用户登录一个特性就搞定
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性。
// 摘要:
// 表示一个特性,该特性用于限制调用方对操作方法的访问。
[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>
使用实例:
//...省略引用
namespace MrHuo.Framework.Blog
{
[Authorization]//如果将此特性加在Controller上,那么访问这个Controller里面的方法都需要验证用户登录状态
public class UserController:Controller
{
[AllowAnonymous]//这里是一个特例,有这个特性,表示这个方法不需要验证用户登录状态
public ActionResult Index()
{
//...省略具体代码
}
//这里的方法需要验证登录状态,以下雷同
public ActionResult Create()
{
//...省略具体代码
}
}
}
转:C4项目中验证用户登录一个特性就搞定的更多相关文章
- MVC4项目中验证用户登录一个特性就搞定
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- [转]MVC4项目中验证用户登录一个特性就搞定
本文转自:http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Log ...
- Vue项目中实现用户登录及token验证
学习博客:https://www.cnblogs.com/web-record/p/9876916.html
- flask中验证用户登录的装饰器
from flask import Flask,render_template,redirect,request,session from functools import wraps app = F ...
- easyui datagrid 禁止选中行 EF的增删改查(转载) C# 获取用户IP地址(转载) MVC EF 执行SQL语句(转载) 在EF中执行SQL语句(转载) EF中使用SQL语句或存储过程 .net MVC使用Session验证用户登录 PowerDesigner 参照完整性约束(转载)
easyui datagrid 禁止选中行 没有找到可以直接禁止的属性,但是找到两个间接禁止的方式. 方式一: //onClickRow: function (rowIndex, rowData) ...
- 单点登录CAS使用记(三):实现自定义验证用户登录
问题: CAS自带的用户验证逻辑太过简单,如何像正常网站一样,通过验证DB中的用户数据,来验证用户以及密码的合法性呢? 方案1:CAS默认的JDBC扩展方案: CAS自带了两种简单的通过JDBC方式验 ...
- 通过配置http拦截器,来进行ajax请求验证用户登录的页面跳转
在.NET中验证用户是否登录或者是否过期,若需要登录时则将请求转向至登录页面. 这个流程在进行页面请求时是没问题的,能正确进行页面跳转. 然而在使用xmlhttprequest时,或者jq的getJs ...
- MVC4验证用户登录特性实现方法
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- Asp.Net使用加密cookie代替session验证用户登录状态 源码分享
首先 session 和 cache 拥有各自的优势而存在. 他们的优劣就不在这里讨论了. 本实例仅存储用户id于用户名,对于多级权限的架构,可以自行修改增加权限字段 本实例采用vs2010编写 ...
随机推荐
- web_profile(网站分析)配置
web_profiler: # DEPRECATED, it is not useful anymore and can be removed # safely from your configura ...
- shell之变量替换:临时替换
${FILE:-word} 若变量为空,给变量FILE添加一个临时默认值word,FILE本身值并不变化eg: FILE1=${FILE:-word} 若FILE为空,则赋予FILE1值word $ ...
- 【转】Tomcat集群Cluster实现原理剖析
此文章来源:http://zyycaesar.iteye.com/blog/296606 此文章作者:zyycaesar 对于WEB应用集群的技术实现而言,最大的难点就是如何能在集群中的多个节点之间保 ...
- project euler 26:Reciprocal cycles
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with d ...
- LFS,编译自己的Linux系统 - 准备
概述 现在用的操作系统是Win8.1,用VMware创建一个虚拟机,3G内存(物理内存是6G,分一半),23G硬盘,其中3G用于swap分区,10G用于host system,10G用于建立LFS系统 ...
- Typecho 代码阅读笔记(二) - 数据库访问
转载请注明出处:http://blog.csdn.net/jh_zzz 这一块比较复杂,我还没有完全理解为什么要把 SQL 语句的组装搞这么复杂. 从一个普通皮肤页面开始 themes/default ...
- 如何为WPF添加Main()函数 程序入口点的修改
一般的.WPF的Main()函数是自动生成的,不过有时候我们需要为我们的应用程序传参.那么自动生成的Main()函数就不会满足我们的要求. 那么如何为WPF Application 设置Main()函 ...
- Farming
Problem Description You have a big farm, and you want to grow vegetables in it. You're too lazy to s ...
- Cdev
1,#和##操作符Operator,使用 首个参数返回为一个带引号的字符串 predefined variable was not declared in the scope;
- 【转】android 电池(二):android关机充电流程、充电画面显示
关键词:android 电池关机充电 androidboot.mode charger关机充电 充电画面显示 平台信息:内核:linux2.6/linux3.0系统:android/android4. ...