简体   繁体   English

什么时候覆盖ActionFilterAttribute.OnActionExecutingAsync()?

[英]When to override ActionFilterAttribute.OnActionExecutingAsync()?

I'm implementing a custom ActionFilterAttribute and it's currently not clear whether I need to override the OnActionExecutingAsync() method. 我正在实现自定义ActionFilterAttribute ,目前尚不清楚是否需要重写OnActionExecutingAsync()方法。 This is a project that uses ASP.NET WebAPI v5.2.3. 这是一个使用ASP.NET WebAPI v5.2.3的项目。

I've currently overridden both OnActionExecuting() and OnActionExecutingAsync() , where both methods call the same private method that does the actual work of the filter. 我目前已经覆盖了OnActionExecuting()OnActionExecutingAsync() ,这两个方法都调用执行过滤器实际工作的同一私有方法。

What I find is that both methods are getting called - first OnActionExecutingAsync() and then - from within the call to base.OnActionExecutingAsync() - OnActionExecuting() gets called. 我发现这两种方法都被调用-首先是OnActionExecutingAsync() ,然后是从对base.OnActionExecutingAsync()的调用内-调用了OnActionExecuting()

So do I only need to override OnActionExecuting() ? 那我只需要重写OnActionExecuting()吗? If so, when would I ever need to override the async version? 如果是这样,我什么时候需要覆盖异步版本?

I think you'll run into problems trying to use OnActionExecuting on an async controller because it won't be able to communicate the CancellationToken that the system uses to manage threads. 我认为您在尝试在异步控制器上使用OnActionExecuting时会遇到问题,因为它将无法传达系统用于管理线程的CancellationToken You might find that OnActionExecuting fires on resumption of an action after an await , which might be a problem depending on what your filter is expecting, for example. 您可能会发现OnActionExecutingawait之后恢复操作时触发,例如,这可能取决于过滤器的预期而成为问题。

Based on some experimentation though, it appears that OnActionExecutingAsync works fine with non-async controllers. 但是,基于一些实验,似乎OnActionExecutingAsync与非异步控制器可以正常工作。

So do I only need to override OnActionExecuting()? 那我只需要重写OnActionExecuting()吗? If so, when would I ever need to override the async version? 如果是这样,我什么时候需要覆盖异步版本?

Only if you have a long running task in your filter. 仅当您的过滤器中有长期运行的任务时。

Usually, when ever a method has an async version and a sync version both of them will call and you should just override or hook to one of them. 通常,当某个方法具有异步版本和同步版本时,它们都会被调用,并且您应该覆盖或钩接到其中一个。 For this case, you could check it in this link 对于这种情况,您可以在链接中进行检查

    [NonAction]
    public virtual async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (next == null)
        {
            throw new ArgumentNullException(nameof(next));
        }

        OnActionExecuting(context);
        if (context.Result == null)
        {
            OnActionExecuted(await next());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM