4

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.

Tufan Chand
  • 692
  • 4
  • 19
  • 36
  • 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. – Georgi Georgiev Feb 26 '19 at 10:55
  • 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? @GeorgiGeorgiev – Tufan Chand Feb 26 '19 at 13:50

2 Answers2

10
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    bool valid=SomeMethod();
    if(valid)
         await next();
    else
        context.Result = new BadRequestObjectResult("Invalid!");
}
Paddy
  • 33,309
  • 15
  • 79
  • 114
Tufan Chand
  • 692
  • 4
  • 19
  • 36
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")
    }
Georgi Georgiev
  • 3,854
  • 5
  • 29
  • 39
  • 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"); – Tufan Chand Feb 27 '19 at 09:14