[英]Async OnActionExecuting in ASP.NET Core's ActionFilterAttribute
ASP.NET Core's ActionFilterAttribute
has these: ASP.NET Core 的
ActionFilterAttribute
有这些:
public virtual void OnActionExecuting(ActionExecutingContext context);
public virtual void OnActionExecuted(ActionExecutedContext context);
public virtual Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);
I need an async version of OnActionExecuting
, which doesn't exist.我需要一个不存在的
OnActionExecuting
异步版本。
However I have a feeling that I can use OnActionExecutionAsync
instead, as it also has an argument of ActionExecutingContext
.但是我有一种感觉,我可以使用
OnActionExecutionAsync
代替,因为它也有一个ActionExecutingContext
参数。
Am I correct that despite the name, they trigger at the same point in the process?尽管名称不同,但它们在过程中的同一点触发,我是否正确?
Also, what do I need to do with the next
argument?另外,我需要对
next
论点做什么? Once I'm done with my stuff, do I simply need to call await next()
?一旦我完成了我的工作,我是否只需要调用
await next()
?
Is that it?是这样吗? I'm unsure as I can't find docs for this.
我不确定,因为我找不到这方面的文档。
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.异步过滤器的工作方式略有不同:首先执行必须在动作之前执行的代码,为实际逻辑调用
next()
,最后添加要在动作之后执行的代码。
public async Task OnActionExecutionAsync(ActionExecutingContext context,
ActionExecutionDelegate next)
{
// logic before action goes here
await next(); // the actual action
// logic after the action goes here
}
The documentation is here: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#implementation文档在这里: https : //docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters#implementation
Asynchronous filters always take precedence over the synchronous filter implementations.
异步过滤器始终优先于同步过滤器实现。
However, you can manage to have both.但是,您可以设法同时拥有两者。 For instance:
例如:
public class TimestampFilter : IActionFilter, IAsyncActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
context.ActionDescriptor.RouteValues["timestamp"] = DateTime.Now.ToString();
}
public void OnActionExecuted(ActionExecutedContext context)
{
var ts = DateTime.Parse(context.ActionDescriptor. RouteValues["timestamp"]).AddHours(1).ToString();
context.HttpContext.Response.Headers["X-EXPIRY-TIMESTAMP"] = ts;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
this.OnActionExecuting(context);
var resultContext = await next();
this.OnActionExecuted(resultContext);
}
}
An ever better pattern:一个更好的模式:
public override async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
try
{
//do your async things here
}
finally
{
await base.OnActionExecutionAsync(context, next); <--- notice this!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.