Do something before you act in Web API 2

I want to do something before some actions of my web API. How to throw an error ...

public class OnlyAuthorized : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (!IsValidAuthorization(actionExecutedContext.Request.Headers.Authorization?.Parameter))
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }

        actionExecutedContext.Response?.Headers.Add("Access-Control-Allow-Origin", "*");
        base.OnActionExecuted(actionExecutedContext);
    }

    public bool IsValidAuthorization(string token)
    {
        return token != null;
    }
}

But it is executed after the action, not before it. Thus, the logic of the action is always achieved, despite the fact that sometimes the request is not allowed to perform the action.

How can i do this?

If this cannot be done with attributes, I think I can deal with a solution where I can intercept all POST requests.

+4
source share
1 answer

OnActionExecuted OnActionExecuting . https://msdn.microsoft.com/en-us/library/system.web.http.filters.actionfilterattribute(v=vs.118).aspx

OnActionExecuted(ActionExecutedContext): ASP.NET MVC .

OnActionExecuting(ActionExecutingContext): ASP.NET MVC ,

+3

All Articles