Understanding Action Filters (C#) 可以用来做权限检查
比如需要操作某一张表league的数据,multi-tenancy的模式,每一行数据都有一个租户id的字段。
那么在api调用操作的时候,我们需要检查league的id,是否和当前用户所属的租户信息一致。防止传递了假信息。处理越权访问的问题。
Understanding Action Filters
The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:
- OutputCache – This action filter caches the output of a controller action for a specified amount of time.
- HandleError – This action filter handles errors raised when a controller action executes.
- Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter that logs different stages of the processing of an action to the Visual Studio Output window.
The Base ActionFilterAttribute Class
In order to make it easier for you to implement a custom action filter, the ASP.NET MVC framework includes a base ActionFilterAttribute
class. This class implements both the IActionFilter
and IResultFilter
interfaces and inherits from the Filter
class.
The terminology here is not entirely consistent. Technically, a class that inherits from the ActionFilterAttribute class is both an action filter and a result filter. However, in the loose sense, the word action filter is used to refer to any type of filter in the ASP.NET MVC framework.
The base ActionFilterAttribute
class has the following methods that you can override:
- OnActionExecuting – This method is called before a controller action is executed.
- OnActionExecuted – This method is called after a controller action is executed.
- OnResultExecuting – This method is called before a controller action result is executed.
- OnResultExecuted – This method is called after a controller action result is executed.
In the next section, we'll see how you can implement each of these different methods.
针对数据越权操作,进行数据的权限检查
public class LeaguePermissionActionFilter : ActionFilterAttribute
{
/// <summary>
/// This method is called before a controller action is executed.
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameterName = "model";
var parameter = filterContext.ActionParameters[parameterName];
LeagueTableBaseDtoModel model = parameter as LeagueTableBaseDtoModel;
var permissionCheckResult = PermissionCheckHelper.PermissionCheckByLeagueTableId(model.LeagueTableId);
if (permissionCheckResult.Status == OperationStatus.Failed)
{
filterContext.Result =
new HttpStatusCodeResult(HttpStatusCode.Forbidden, permissionCheckResult.Message);
} base.OnActionExecuting(filterContext);
}
}
参数检查不合格,进行页面跳转
Redirect From Action Filter Attribute
Set filterContext.Result
With the route name:
filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);
You can also do something like:
filterContext.Result = new ViewResult
{
ViewName = SharedViews.SessionLost,
ViewData = filterContext.Controller.ViewData
};
If you want to use RedirectToAction
:
You could make a public RedirectToAction
method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction
from System.Web.Mvc.Controller
. Adding this method allows for a public call to your RedirectToAction
from the filter.
public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
return base.RedirectToAction(action, controller);
}
Then your filter would look something like:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (SomeControllerBase) filterContext.Controller;
filterContext.Result = controller.RedirectToAction("index", "home");
}
参数检查 不跳转400,直接返回json result
返回的结果是jsonresult
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var httpResponseBase = filterContext.HttpContext.Response;
httpResponseBase.StatusCode = (int) HttpStatusCode.BadRequest;
httpResponseBase.StatusDescription = "Invalid Model State";
var errorMessage = ModelState.Values.First(v => v.Errors.Count > ).Errors[].ErrorMessage;
LogUtil.CreateLog(LogLevel.Error, errorMessage);
filterContext.Result = new JsonResult
{
Data = new ReturnMessage
{
Status = OperationStatus.Failed,
Message = errorMessage
}
};
} base.OnActionExecuting(filterContext);
}
Understanding Action Filters (C#) 可以用来做权限检查的更多相关文章
- asp.net 使用IHttpModule 做权限检查 登录超时检查(转)
IHttpModule 权限 检查 登录超时检查 这样就不需要每个页面都做一次检查 也不需要继承任何父类. using System;using System.Collections.Generic; ...
- Action Filters for ASP.NET MVC
本文主要介绍ASP.NET MVC中的Action Filters,并通过举例来呈现其实际应用. Action Filters 可以作为一个应用,作用到controller action (或整个co ...
- 【Spring】5、利用自定义注解在SpringMVC中实现自定义权限检查
转自:http://www.tuicool.com/articles/6z2uIvU 先描述一下应用场景,基于Spring MVC的WEB程序,需要对每个Action进行权限判断,当前用户有权限则允许 ...
- Mysql 存储过程、函数、触发器和视图的权限检查
当存储过程.函数.触发器和视图创建后,不单单创建者要执行,其它用户也可能需要执行,换句话说,执行者有可能不是创建者本身,那么在执行存储过程时,MySQL是如何做权限检查的? 在默认情况下,MySQL将 ...
- 使用before_request来做权限和用户检查
因为使用restful方式,因此每次用户访问都会上传带入auth_key,如jwt等,因此可在@app.before_request中做权限的检查. @app.app.before_request d ...
- mvc通过ActionFilterAttribute做登录检查
1.0 创建Attribute using System; using System.Collections.Generic; using System.Linq; using System.Web; ...
- Laravel5做权限管理
关于权限管理的思考 最近用laravel设计后台,后台需要有个权限管理.权限管理实质上分为两个部分,首先是认证,然后是权限.认证部分非常好做,就是管理员登录,记录session.这个laravel中也 ...
- 理解ASP.NET MVC Framework Action Filters
原文:http://www.cnblogs.com/darkdawn/archive/2009/03/13/1410477.html 本指南主要解释action filters,action filt ...
- MVC用户登陆验证及权限检查(Form认证)
1.配置Web.conf,使用Form认证方式 <system.web> <authentication mode="None" /> ...
随机推荐
- IntelliJ Idea 依赖包下载成功,代码里无法import问题解决方法
今天clone一个github上的基于maven的项目IntelliJ Idea 依赖包下载成功,代码里无法import.解决方法:删掉原来的.iml,刷新. 如果不行,可尝试:File->In ...
- 【转】VC和VS的区别
各个版本之间的对应关系 使用windows平台搞开发时,下载第三方库时经常会遇到文件名以VCxx版本号命令,VC版本如何转换成对应的VS的版本呢,这里总结一下vc和vs的关系. Microsoft V ...
- mysql学习之基础篇02
我们来说一下表的增删改查的基本语法: 首先建立一个简单的薪资表: create table salary(id int primary key auto_increment,sname varchar ...
- Android AIDL使用详解_Android IPC 机制详解
一.概述 AIDL 意思即 Android Interface Definition Language,翻译过来就是Android接口定义语言,是用于定义服务器和客户端通信接口的一种描述语言,可以拿来 ...
- 用js刷剑指offer(把数组排成最小的数)
题目描述 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 思路 对ve ...
- python 全局声明 global
https://www.cnblogs.com/Lin-Yi/p/7305364.html 在基本的python语法当中,一个函数可以随意读取全局数据,但是要修改全局数据的时候有两种方法:1 glob ...
- Kotlin继承与重写重要特性剖析
继续Kotlin的面向对象之旅. 继承: 在Java中我们知道除了final类不能被继承,其它的情况都是可以被继承的,而在Kotlin中的规则是这样的:“在Kotlin中,所有类在默认情况下都是无法被 ...
- URL路径详解
1.url http://localhost:8080/Test/1.html url表示浏览器访问服务器的网络路径 http:相当于人们交流时候的语言 :// 分隔符 localhost ...
- 2019ICPC徐州网络赛 A.Who is better?——斐波那契博弈&&扩展中国剩余定理
题意 有一堆石子,两个顶尖聪明的人玩游戏,先取者可以取走任意多个,但不能全取完,以后每人取的石子数不能超过上个人的两倍.石子的个数是通过模方程组给出的. 题目链接 分析 斐波那契博弈有结论:当且仅当石 ...
- 集合(Collection)类
集合(Collection)类是专门用于数据存储和检索的类.这些类提供了对栈(stack).队列(queue).列表(list)和哈希表(hash table)的支持.大多数集合类实现了相同的接口. ...