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?
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.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With