Returns from OnActionExecutionAsync without executing the action in asp.net core

Tufan Chand picture Tufan Chand · Feb 26, 2019 · Viewed 8k times · Source

Here I want to return from the custom action filter without executing the controller action method in asp.net core WEB API.

Below is my requirement with sample code.

public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    bool valid=SomeMethod();
    if(valid)
        //executes controller action
    else
        //returns without executing controller action with the custom message (if possible)
}

I have searched and found some related questions and answers but nothing worked for me.

Found this await base.OnActionExecutionAsync(context, next); but it skips the remaining logic of filters and directly executing the controller action so didn't work for mine scenario.

Answer

Tufan Chand picture Tufan Chand · Mar 1, 2019
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    bool valid=SomeMethod();
    if(valid)
         await next();
    else
        context.Result = new BadRequestObjectResult("Invalid!");
}