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); }