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 > 0).Errors[0].ErrorMessage; LogUtil.CreateLog(LogLevel.Error, errorMessage); filterContext.Result = new JsonResult { Data = new ReturnMessage { Status = OperationStatus.Failed, Message = errorMessage } }; } base.OnActionExecuting(filterContext); }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-10-14 C#中this在构造函数时的使用
2015-10-14 Monitor vs WaitHandle