MVC 4 中的异步操作过滤器 [英] Async action filter in MVC 4

查看:47
本文介绍了MVC 4 中的异步操作过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作过滤器,当在某些特定条件下使用时,它必须执行网络服务调用以确保当前状态有效.这最初似乎是 async/await 的理想选择,但我遇到了一个障碍:

I have an action filter that when used in certain specific conditions has to perform a web service call to ensure that the current state is valid. This initially seemed like an ideal candidate for async/await, but I have encountered a snag:

假设一个请求到:/Test/FilteredAction

Assume a request to: /Test/FilteredAction

  • MyCustomActionFilter 开始执行
    • 到达第一个await"语句

    传统上,我希望操作过滤器恢复执行,然后在控制器操作开始执行之前完成,但事实并非如此.

    Traditionally I would expect the action filter to resume executing and then complete before the controller action starts executing, but this does not happen.

    现在我假设这是因为我正在使用:

    Now I assume this is because I am using:

    public class MyCustomActionFilter : ActionFilterAttribute 
    {
        public override **async** void OnActionExecuting(FilterContext context) 
        {
            var foo = await WebServiceCall();
        }
    }
    

    所以我想我的问题是:MVC 4 中是否有一个异步感知动作过滤器类,或者我应该阻止这里的调用?

    So I think my question is: Is there an async-aware action filter class built into MVC 4, or should I just block on the calls in here?

    推荐答案

    MVC 没有与 async 兼容的操作过滤器(但 WebAPI 确实有一个).

    MVC does not have an async-compatible action filter (but WebAPI does have one).

    目前,我建议您在 OnActionExecuting 中使用阻塞调用.希望MVC在未来会有更好的故事.

    For now, I recommend you use blocking calls in OnActionExecuting. Hopefully MVC will have a better story in the future.

    更新:您可以在此处投票让 MVC 团队添加 async 过滤器.

    Update: You can vote here for the MVC team to add async filters.

    这篇关于MVC 4 中的异步操作过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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