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

2

5

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.

Trivia answered 26/2, 2019 at 9:57 Comment(2)
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. This is the standard behaviour. You either short-circuit the request inside the filter or let the action execute. What are you trying to do? If you have multiple action filters the one that short-circuits the request is the last one executed.Lavelle
yes, I am aware this is the standard behavior of base.OnAc.......Here I am checking one parameter of the request and validate it based on some logic. if it's false then it shouldn't execute the controller action or if any filters as well. Is this possible or Am I looking for something impossible? @GeorgiGeorgievTrivia
T
12
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    bool valid=SomeMethod();
    if(valid)
         await next();
    else
        context.Result = new BadRequestObjectResult("Invalid!");
}
Trivia answered 1/3, 2019 at 12:18 Comment(0)
L
2

You can short-circuit by setting context.Result to any valid implementation of IActionResult. The below example just returns the error as plain text. If you want some fancy error message you can use View() instead.

public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        bool valid=SomeMethod();
        if(valid)
             next();
        else
            context.Result = Content("Failed to validate")
    }
Lavelle answered 26/2, 2019 at 15:23 Comment(1)
This is not exactly the answer as I am not able to find anything as Content, but your answer helped me to get the solution. Thank you very much. I have replaced like this....... context.Result = new BadRequestObjectResult("Invalid");Trivia

© 2022 - 2024 — McMap. All rights reserved.