简体   繁体   中英

How to fire OnActionExecuting in Web Api controller?

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 Request object to lookup if the request has the authorization token?

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM