I want to create a web api filter that checks if the request header has the correct Api key.
If it doesn't, I want to return 403 response code and halt execution (forbidden action)
public class ApiPermission : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
}
Using the filterContext I know I can do something like:
filterContext.Result = new RedirectTo...
But how can I change the status code to 403 and just return a string and halt execution and stop processing other filters and the controller action?
Looks like posted answers not Asp.Net Core 2.1 compatible. In core you can do something like that
filterContext.Result = new ObjectResult(actionContext.ModelState)
{
Value = null,
StatusCode = StatusCodes.Status403Forbidden
};
Or maybe it'll be convenient to create class like BadRequest, but for 403 Code.
public class ForbiddenObjectResult : ObjectResult
{
public ForbiddenObjectResult(object value)
: base(value)
{
StatusCode = StatusCodes.Status403Forbidden;
}
}
...
filterContext.Result = new ForbiddenObjectResult(filterContext.ModelState);
If you don't want to throw an exception, you can instead return an HttpStatusCodeResult
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Result != null) return; //Another filter has already returned a result so pass it on
//Do your filtering
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Forbidden");
}
In .NET core (I'm using 3.0), you can make sure code does not subsequently reach the controller action by using the following in the action filter:
filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
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