我有一个包含以下代码的同步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)运行该模块时,我收到以下错误.@H_404_5@
An asynchronous operation cannot be started at this time. Asynchronous
operations may only be started within an asynchronous handler or
module or during certain events in the Page lifecycle. If this
exception occurred while executing a Page,ensure that the Page is
marked <%@ Page Async=”true” %>.@H_404_5@
我似乎错过了一些东西但是通过我的阅读,错误实际上不应该发生.@H_404_5@
我有一个挖掘,但我似乎无法找到任何帮助,有没有人有任何想法?@H_404_5@
解决方法
因此,您在同步HttpModule事件处理程序中具有异步代码,并且ASP.NET抛出异常,指示异步操作只能在异步处理程序/模块中启动.对我来说似乎很简单.
要解决此问题,您不应直接订阅BeginRequest;相反,创建一个返回任务的“处理程序”,将其包装在EventHandlerTaskAsyncHelper
中,并将其传递给AddOnBeginRequestAsync
.@H_404_5@
像这样的东西:@H_404_5@
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);