我有一个包含以下代码的同步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应用程序(NET4.5)运行模块时,我会得到以下错误。
此时无法启动异步操作。异步操作只能在异步处理程序或模块中启动,或者在页生命周期中的某些事件期间启动。如果在执行页时发生此异常,请确保该页标记为<%@ Page Async="true“%>。
我似乎遗漏了一些东西,但根据我的解读,错误不应该实际发生。
我已经挖了一遍,但我似乎找不到任何帮助,有人有什么想法吗?
发布于 2013-07-25 17:49:39
因此,同步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);https://stackoverflow.com/questions/17863503
复制相似问题