【问题标题】:Asynchronous HttpModule MVC异步 HttpModule MVC
【发布时间】:2013-07-25 16:04:33
【问题描述】:

我有一个包含以下代码的同步 HttpModule。

    /// <summary>
    /// Occurs as the first event in the HTTP pipeline chain of execution 
    /// when ASP.NET responds to a request.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">An <see cref="T:System.EventArgs">EventArgs</see> that 
    /// contains the event data.</param>
    private async void ContextBeginRequest(object sender, EventArgs e)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        await this.ProcessImageAsync(context);
    }

当我尝试从空的 MVC4 应用程序 (NET 4.5) 运行模块时,出现以下错误。

此时无法启动异步操作。异步 操作只能在异步处理程序中启动或 模块或页面生命周期中的某些事件期间。如果这 执行页面时发生异常,请确保该页面是 标记为 。

我似乎遗漏了一些东西,但根据我的阅读,错误实际上不应该发生。

我四处寻找,但似乎找不到任何帮助,有人有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc async-await httpmodule


    【解决方案1】:

    因此,您在同步 HttpModule 事件处理程序中有异步代码,并且 ASP.NET 会引发异常,指示异步操作只能在异步处理程序/模块中启动。对我来说似乎很简单。

    要解决此问题,您不应直接订阅BeginRequest;相反,创建一个Task-returning“处理程序”,将其包装在EventHandlerTaskAsyncHelper 中,并将其传递给AddOnBeginRequestAsync

    类似这样的:

    private async Task ContextBeginRequest(object sender, EventArgs e)
    {
      HttpContext context = ((HttpApplication)sender).Context;
      await ProcessImageAsync(context);
    
      // Side note; if all you're doing is awaiting a single task at the end of an async method,
      //  then you can just remove the "async" and replace "await" with "return".
    }
    

    并订阅:

    var wrapper = new EventHandlerTaskAsyncHelper(ContextBeginRequest);
    application.AddOnBeginRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
    

    【讨论】:

    • 这一定是你帮助我的好几次了,谢谢!我应该说对不起,代码实际上是用 Net 4.0 编写的,并且使用 BCL 库来支持 async 关键字,所以我可以同时支持 4.0 和 4.5。因此,我无法使用 EventHandlerTaskAsyncHelper。
    • 啊,不幸的是,Microsoft.Bcl.Asyncundefined behavior on ASP.NET 4.0。在 ASP.NET 上,您必须在 .NET 4.5 上运行,而不是在 .NET 4.0 上运行。
    • 啊,好吧...所以,如果我从 web.config 中的 &lt;httpRuntime /&gt; 节点中删除 targetFramework="4.5" 来测试这个,这是可行的。这是否意味着在 NET 4.0 中我的 httpModule 实际上不是异步的?这是否也意味着我不能在没有 EventHandlerTaskAsyncHelper 的情况下将异步 httpModule 与 MVC 一起使用,或者还有其他方法。老实说,我仍然对它抛出错误感到困惑。消息似乎说 httpModules 没问题。
    • 我相信您将“作品”定义为“不引发异常”。再看一下博客文章:如果您在 .NET 4.0 上编写 ASP.NET,那么您不能使用asyncMicrosoft.Bcl.Async 不会 反转这个) . ASP.NET 的一些核心部分在 .NET 4.5 中被重写以正确支持 async(尤其是 SynchronizationContext),而这些在 .NET 4.0 上根本不可用。
    • BCL 提供核心 (.NET) 行为,但 ASP.NET 有它自己需要的行为(而 BCL 不提供)。所以Microsoft.Bcl.Async 将为 .NET 4.0 桌面应用程序带来完整的async 支持,但不支持 ASP.NET 应用程序。如果您需要同时支持两者,那么编译时条件是一种方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多