MVC之ActionFilterAttribute自定义属性
ActionFilterAttribute里有OnActionExecuting方法,跟Controller一样, 同是抽象实现了IActionFilter接口。
// 登录认证特性
public class AuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } }); base.OnActionExecuting(filterContext);
}
}
使用方法如下:
public class HomeController : Controller
{
[Authentication]
public ActionResult Index()
{
return View();
}
}
如果你想针对整个MVC项目的所有Action都使用此过滤器,步骤如下:
a. 确保Global.asax.cs的Application_Start方法中包含如下红色行:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
b. 在FilterConfig.cs文件中注册相应的特性过滤器:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthenticationAttribute());
}
}
如此,通过过滤器的方法实现认证和授权
另有不推荐的方法实现授权功能,自定义一个控制器类,再通过继承这个控制器类:
1、继承Controller:
1.1 参考WebForm使用方式,在派生类里自己添加了验证方法,然后在每个Action方法里调用。
派生类如下:
public class AuthenticationControllor : Controller
{
public bool Validate()
{
if (Session["username"] == null)
return false;
else
return true;
} public ActionResult RedirectLogin(bool redirect = true)
{
if (redirect)
return RedirectToAction("Login", "Home", new { from = Request.Url.ToString() });
else
return RedirectToAction("Login", "Home");
}
}
使用类如下:
public class HomeController : AuthenticationControllor
{
public ActionResult Index()
{
if (!Validate())
return RedirectLogin(); return View();
}
}
1.2 改进上面的使用,通过用Controller里有一个OnActionExecuting方法,此方法是在Action之前执行的,非常方便。
派生类如下:
public class AuthenticationControllor : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session["username"] == null)
filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } }); base.OnActionExecuting(filterContext);
}
}
使用类如下:
// 不需要多写任何逻辑代码就能判断是否登录并跳转
public class HomeController : AuthenticationControllor
{
public ActionResult Index()
{
return View();
}
}
/// <summary>
/// 权限拦截
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class PermissionFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// 权限拦截
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!this.CheckAnonymous(filterContext))
{
//未登录验证
if (SessionHelper.Get("UserID") == null)
{
//跳转到登录页面
filterContext.RequestContext.HttpContext.Response.Redirect("~/Admin/User/Login");
}
}
}
/// <summary>
/// [Anonymous标记]验证是否匿名访问
/// </summary>
/// <param name="filterContext"></param>
/// <returns></returns>
public bool CheckAnonymous(ActionExecutingContext filterContext)
{
//验证是否是匿名访问的Action
object[] attrsAnonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AnonymousAttribute), true);
//是否是Anonymous
var Anonymous = attrsAnonymous.Length == ;
return Anonymous;
}
}
通过写一个BaseController来进行权限的验证,这样就不需要所有需要验证的Controller加标注了,当然BaseController还可以增加其他通用的处理
/// <summary>
/// Admin后台系统公共控制器(需要验证的模块)
/// </summary>
[PermissionFilter]
public class BaseController:Controller
{ }
其它文章 :
http://www.cnblogs.com/sunkaixuan/p/4908773.html
MVC之ActionFilterAttribute自定义属性的更多相关文章
- MVC中ActionFilterAttribute用法并实现统一授权
MVC中ActionFilterAttribute经常用来处理权限或者统一操作时的问题. 先写一个简单的例子,如下: 比如现在有一个用户管理中心,而这个用户管理中心需要登录授权后才能进去操作或浏览信息 ...
- mvc通过ActionFilterAttribute做登录检查
1.0 创建Attribute using System; using System.Collections.Generic; using System.Linq; using System.Web; ...
- 创建一个ASP.NET MVC OutputCache ActionFilterAttribute
在每一个web应用程序中, 有的情况下,你想在一段时间内缓存一个具体的页面HTML输出,因为相关的数据和处理并不是总是变化.这种缓存的响应是储存在服务器的内存中.因为没有必要的额外处理,它提供了非常快 ...
- ASP.NET MVC 利用ActionFilterAttribute来做权限等
ActionFilterAttribute是Action过滤类,该属于会在执行一个action之前先执行.而ActionFilterAttribute是 MVC的一个专门处理action过滤的类.基于 ...
- MVC 过滤器 ActionFilterAttribute
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- ASP.NET MVC 通过ActionFilterAttribute来实现防止重复提交
实现思想:每个页面打开的时候会在页面的隐藏控件自动生成一个值并将这个值赋值session,当提交方法的时候会在过滤器的时候进行获取session和页面传值过来的隐藏控件的值进行比较,如果值相同的话,重 ...
- MVC之ActionFilterAttribute
1.登录页面代码: @{ ViewBag.Title = "会员登录"; Layout = "~/Views/Shared/_LayoutDialog.cshtml&qu ...
- MVC过滤器-->ActionFilterAttribute和HandleErrorAttribute
自定义的action过滤器 需要继承自ActionFilterAttribute 接口 OnActionExecuting: 在方法执行之前执行 OnActionExecuted: 方法的逻辑代 ...
- mvc 4 ActionFilterAttribute 特性,进行权限验证
权限验证: /// <summary> /// 管理员身份验证 /// </summary> public class BasicAuthenticationAttribute ...
随机推荐
- UVA548 Tree (二叉树的遍历)
You are to determine the value of the leaf node in a given binary tree that is the terminal node of ...
- 微信小程序开发教程(九)视图层——.wxss详解
WXSS是一套样式语言,用于描述WXML的组件样式. 官方文档表示,WXSS的选择器目前支持(“.class”.“#id”.“elemnt”.“element,element”.“::after”.“ ...
- [PKUSC2018]最大前缀和(DP)
题意:求一个序列随机打乱后最大前缀和的期望. 考场上发现不管怎么设状态都写不出来,实际上只要稍微转换一下就好了. 一个前缀[1..k]是最大前缀,当且仅当前面的所有后缀[k-1,k],[k-2,k], ...
- 记一次深刻的教训-----将mat数据转化为SequenceFile
深刻的体会就是,“java.lang.NullPointer.Exception”就是空指针异常可能是由于数组部分元素未被初始化引起的. 1)使用jmatio将mat数据转化为SequenceFile ...
- 解决Ubuntu 14下,PhpStorm 9.x 编辑器界面中文乱码的问题
在Ubuntu 14中,安装了 PhpStorm 9.02,发现 软件界面中文乱码,但是源码编辑处却显示正常,如下图所示: 很奇怪,猜想,应该是软件界面字体有问题,选了一个没有包含中文字体的字体.先前 ...
- 解决ThinkPHP3.2.3框架,PDO驱动查询出来的字段名全是小写的bug
找到文件:ThinkPHP\Library\Think\Db\Driver.class.php 找到代码: // PDO连接参数 protected $options = array( PDO::AT ...
- 上手 Webpack ? 这篇就够了!
JavaSript 模块化打包已混迹江湖许久.2009年,RequireJS 就提交了它的第一个版本,Browserify 接踵而至,随后其他打包工具也开始大行其道.最终,Webpack 从其中脱颖而 ...
- js原生创建模拟事件和自定义事件的方法
让我万万没想到的是,原来<JavaScript高级程序设计(第3版)>里面提到的方法已经是过时的了.后来我查看了MDN,才找到了最新的方法. 模拟鼠标事件MDN上已经说得很清楚,尽管为了保 ...
- JavaScript之链式结构序列化1
一.概述 在JavaScript中,链式模式代码,太多太多,如下: if_else: if(...){ //TODO }else if(...){ //TODO }else{ //TODO } swi ...
- tcpreplay 发包速率控制算法研究
一. 序 1.1 tcpreplay历史 Tcpreplay 的作者是Aaron Turner,该项目开始于2000年,早期的功能是对tcpdump等抓包工具生成的网络包(即pcap文件)的回放, ...