MVC4项目中验证用户登录一个特性就搞定
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性。
// 摘要:
// 表示一个特性,该特性用于限制调用方对操作方法的访问。
[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();
}
}
} private String _AuthSaveType = String.Empty;
/// <summary>
/// 获取或者设置一个值,该值表示用来保存登陆信息的方式
/// <para>如果web.config中未定义AuthSaveType的值,则默认为Session保存</para>
/// </summary>
public String AuthSaveType
{
get { return _AuthSaveType.Trim().ToUpper(); }
set
{
if (String.IsNullOrEmpty(value))
{
throw new ArgumentNullException("用于保存登陆信息的方式不能为空,只能为【Cookie】或者【Session】!");
}
else
{
_AuthSaveType = value.Trim();
}
}
} /// <summary>
/// 处理用户登录
/// </summary>
/// <param name="filterContext"></param>
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项目中验证用户登录一个特性就搞定
本文转自:http://www.mrhuo.com/Article/Details/470/A-Attribute-For-MVC4-Project-Used-To-Validate-User-Log ...
- 转:C4项目中验证用户登录一个特性就搞定
转:C4项目中验证用户登录一个特性就搞定 在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用 ...
- 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 ...
- MVC4验证用户登录特性实现方法
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- 【转】MVC4验证用户登录特性实现方法
在开发过程中,需要用户登陆才能访问指定的页面这种功能,微软已经提供了这个特性. // 摘要: // 表示一个特性,该特性用于限制调用方对操作方法的访问. [AttributeUsage(Attribu ...
- easyui datagrid 禁止选中行 EF的增删改查(转载) C# 获取用户IP地址(转载) MVC EF 执行SQL语句(转载) 在EF中执行SQL语句(转载) EF中使用SQL语句或存储过程 .net MVC使用Session验证用户登录 PowerDesigner 参照完整性约束(转载)
easyui datagrid 禁止选中行 没有找到可以直接禁止的属性,但是找到两个间接禁止的方式. 方式一: //onClickRow: function (rowIndex, rowData) ...
- 从零开始实现asp.net MVC4框架网站的用户登录以及权限验证模块 详细教程
从零开始实现asp.net MVC4框架网站的用户登录以及权限验证模块 详细教程 用户登录与权限验证是网站不可缺少的一部分功能,asp.net MVC4框架内置了用于实现该功能的类库,只需要简单搭 ...
- 单点登录CAS使用记(三):实现自定义验证用户登录
问题: CAS自带的用户验证逻辑太过简单,如何像正常网站一样,通过验证DB中的用户数据,来验证用户以及密码的合法性呢? 方案1:CAS默认的JDBC扩展方案: CAS自带了两种简单的通过JDBC方式验 ...
随机推荐
- Android网络编程基础
Android网络编程只TCP通信 TCP 服务器端工作的主要步骤如下.步骤1 调用ServerSocket(int port)创建一个ServerSocket,并绑定到指定端口上.步骤2 调用acc ...
- LeetCode 1 Two Sum(二分法)
题目来源:https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that t ...
- Monyer's Game 11~15关过关方法
到目前为止,玩这个小游戏并过关的人数已经达到了81人,首先Monyer要感谢各位的捧场与支持.继续上次的<Monyer's Game 6~10关过关方法>,我们来看剩下几关的过关方法. 但 ...
- 【Adaboost算法】C++转C, 分类器结构设计
一.参考OpenCV的CascadeClassifier类LBPEvaluator类 如下,筛选出存放分类器相关信息的成员变量: class CV_EXPORTS_W CascadeClassifie ...
- 每日Scrum--No.6
Yesterday:组内各种乱八七糟的问题,还有自己的效率问题 Today:进行小范围的测试实验 Problem:在显示各景点构成的邻接矩阵的时候,第一次编译未出现任何错误的提示,但是在程序运行时,无 ...
- 将Session写入Memcache
通过session_set_save_handler()方法自定义Session写入Memcache <?php class MemSession{ private static $handle ...
- Altium Designer PCB制作入门实例
概要:本章旨在说明如何生成电路原理图.把设计信息更新到PCB文件中以及在PCB中布线和生成器件输出文件.并且介绍了工程和集成库的概念以及提供了3D PCB开发环境的简要说明.欢迎使用Altium De ...
- xamarin.android 沉浸式状态栏
public class SystemBarTintManager { /** * The default system bar tint color value. */ public static ...
- 用VB实现点名程序
用vb实现点名程序主要是随机变量的产生和数据的读取和存储以及计时器程序的设计,读取的文件命名为data.txt,书写格式为第一行为总人数下面的每行为一个人名,在应用时最好把data文件和程序文件放在一 ...
- hiveql basic
set hive.cli.print.current.db=true; set hive.mapred.mode=strict; set hive.mapred.mode=nonstrict; SHO ...