C# 如何在 Web Api 控制器中触发 OnActionExecuting?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18919477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fire OnActionExecuting in Web Api controller?
提问by loyalflow
My api endpoints are using asp.net mvc (4) web api controllers.
我的 api 端点正在使用 asp.net mvc (4) web api 控制器。
Are there any events similiar to how mvc has OnActionExecuting?
有没有类似于 mvc 有 OnActionExecuting 的事件?
Also, how to I access the Request object to lookup if the request has the authorization token?
另外,如何访问请求对象以查找请求是否具有授权令牌?
回答by neeKo
Use action filters.
使用动作过滤器。
public class MyActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//use filterContext.HttpContext.Request...
}
}
For your controller action, apply the attribute
对于您的控制器操作,应用属性
[MyActionFilter]
public Action MyAction(...)
{
//...
}
As Satpal mentioned in his comment, you might actually want to use AuthorizeAttributeto authorize access to your actions.
正如 Satpal 在他的评论中提到的,您可能实际上想要使用AuthorizeAttribute来授权对您的操作的访问。
回答by Philip Bergstr?m
Since the filter Niko posted didn't work for me (I'm using the ApiController
class), I implemented this filter:
由于 Niko 发布的过滤器对我不起作用(我正在使用ApiController
该类),我实现了这个过滤器:
public class MyActionFilter : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// pre processing
}
}
Make sure you don't usethe ActionFilter from "System.Web.Mvc.ActionFilterAttribute".
确保您不使用“System.Web.Mvc.ActionFilterAttribute”中的 ActionFilter。