Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a filter that returns a forbidden result

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?

like image 255
public static Avatar asked Sep 17 '14 21:09

public static


3 Answers

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);
like image 70
PilgrimViis Avatar answered Oct 30 '22 11:10

PilgrimViis


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");
}
like image 44
xr280xr Avatar answered Oct 30 '22 10:10

xr280xr


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);
like image 2
firecape Avatar answered Oct 30 '22 11:10

firecape