在ASP.NET Core的ActionFilterAttribute中异步执行 [英] Async OnActionExecuting in ASP.NET Core's ActionFilterAttribute

查看:128
本文介绍了在ASP.NET Core的ActionFilterAttribute中异步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET Core的ActionFilterAttribute具有以下特征:

ASP.NET Core's ActionFilterAttribute has these:

public virtual void OnActionExecuting(ActionExecutingContext context);
public virtual void OnActionExecuted(ActionExecutedContext context);
public virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);

我需要异步版本的OnActionExecuting,该版本不存在.

I need an async version of OnActionExecuting, which doesn't exist.

但是我感觉我可以改用OnActionExecutionAsync,因为它也有一个ActionExecutingContext参数.

However I have a feeling that I can use OnActionExecutionAsync instead, as it also has an argument of ActionExecutingContext.

我是否纠正了这个名字,但它们在过程中的同一时刻触发了吗?

Am I correct that despite the name, they trigger at the same point in the process?

另外,我需要使用next自变量做什么?一旦完成我的工作,我是否只需要打电话给await next()?

Also, what do I need to do with the next argument? Once I'm done with my stuff, do I simply need to call await next()?

是吗?我不确定,因为我找不到为此的文档.

Is that it? I'm unsure as I can't find docs for this.

推荐答案

异步过滤器的工作方式有所不同:首先执行必须在操作之前执行的代码,调用next()获取实际逻辑,最后添加要执行的代码行动之后.

Asynchronous filters work a bit differently: first execute code that must be executed before the action, call next() for the actual logic, finally add code to be executed after the action.

public async Task OnActionExecutionAsync(ActionExecutingContext context, 
                                         ActionExecutionDelegate next)
{

    // logic before action goes here

    await next(); // the actual action

    // logic after the action goes here
}

文档在此处: https://docs .microsoft.com/en-us/aspnet/core/mvc/controllers/filters#implementation

这篇关于在ASP.NET Core的ActionFilterAttribute中异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆