从OnActionExecutionAsync返回而不执行asp.net核心中的操作

问题描述 投票:0回答:2

在这里,我想从custom action filter返回而不执行controller action中的method asp.net core WEB 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所以不适用于我的场景。

c# asp.net-core-mvc action-filter custom-action-filter onactionexecuting
2个回答
0
投票

您可以通过设置context.Result到任何有效的IActionResult实现来进行短路。以下示例仅以纯文本形式返回错误。如果你想要一些花哨的错误信息,你可以使用View()代替。

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

0
投票
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    bool valid=SomeMethod();
    if(valid)
         next();
    else
        context.Result = new BadRequestObjectResult("Invalid!");
}
© www.soinside.com 2019 - 2024. All rights reserved.