我有一个包含以下代码的同步 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) 运行该模块时,出现以下错误。
此时无法启动异步操作。异步
操作只能在异步处理程序中启动,或者
模块或页面生命周期中的某些事件期间。如果这
执行Page时发生异常,请确保该Page是
标记为 。
我似乎遗漏了一些东西,但根据我的阅读,该错误实际上不应该发生。
我已经进行了挖掘,但似乎找不到任何帮助,有人有任何想法吗?
因此,同步 HttpModule 事件处理程序中有异步代码,并且 ASP.NET 会引发异常,指示异步操作只能在异步处理程序/模块内启动。对我来说似乎很简单。
要解决此问题,您不应订阅BeginRequest
直接地;相反,创建一个Task
-返回“处理程序”,将其包装起来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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)