Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire OnActionExecuting in Web Api controller?

Tags:

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?

like image 394
loyalflow Avatar asked Sep 20 '13 14:09

loyalflow


People also ask

How do I register a global filter in Web API?

To apply the filter to all Web API controllers, add it to GlobalConfiguration. Filters. public static class WebApiConfig { public static void Register(HttpConfiguration config) { config. Filters.

How does Web API authorize filter work?

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action. You can apply the filter globally, at the controller level, or at the level of individual actions.

How can I call MVC controller action from Web API?

You just need to make sure that you get your URLs right, so WebApi calls your MVC controller via it's properly qualified route. To test this, write a simple MVC action which returns some Json data and call it in the browser. If you manage to craft the URL correctly you will see the data displayed in the browser.


1 Answers

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

like image 155
Philip Bergström Avatar answered Oct 13 '22 11:10

Philip Bergström