How to fire OnActionExecuting in Web Api controller?

前端 未结 2 1140
臣服心动
臣服心动 2021-01-07 17:38

My api endpoints are using asp.net mvc (4) web api controllers.

Are there any events similiar to how mvc has OnActionExecuting?

Also, how to I access the Req

相关标签:
2条回答
  • 2021-01-07 18:22

    Since the filter Niko posted didn't work for me (I'm using the ApiController class), I implemented this filter:

    public class MyActionFilter : System.Web.Http.Filters.ActionFilterAttribute 
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            // pre processing
        }
    }
    

    Make sure you don't use the ActionFilter from "System.Web.Mvc.ActionFilterAttribute".

    0 讨论(0)
  • 2021-01-07 18:28

    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 AuthorizeAttribute to authorize access to your actions.

    0 讨论(0)
提交回复
热议问题