Returns 来自 OnActionExecutionAsync 而不执行 asp.net 核心中的操作

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

这里我想从custom action filterreturn不执行controlleractionmethodasp.net coreWEB API .

以下是我对样品的要求 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)
}

我搜索并找到了一些相关的问题和答案,但对我没有任何帮助。

找到了这个 await base.OnActionExecutionAsync(context, next); 但它跳过了 filters 的剩余逻辑并直接执行了 controller action 所以不适用于我的场景。

您可以通过将 context.Result 设置为 IActionResult 的任何有效实现来短路。下面的例子只是 returns 错误作为纯文本。如果你想要一些花哨的错误信息,你可以使用 View() 代替。

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