Search code examples
c#asp.net-core-mvcaction-filtercustom-action-filteronactionexecuting

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


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.


Solution

  • public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        bool valid=SomeMethod();
        if(valid)
             await next();
        else
            context.Result = new BadRequestObjectResult("Invalid!");
    }