Asynchronous HttpModule MVC

做~自己de王妃 提交于 2019-12-04 23:16:24

问题


I have a synchronous HttpModule that contains the following code.

    /// <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);
    }

When I try to run the module from an empty MVC4 application (NET 4.5) I get the following error.

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" %>.

I'm missing something it seems but by my reading that the error shouldn't actually occur.

I've had a dig around but I cannot seem to find anything to help, does anyone have any ideas?


回答1:


So you have asynchronous code in a synchronous HttpModule event handler, and ASP.NET throws an exception indicating that asynchronous operations may only be started within an asynchronous handler/module. Seems pretty straightforward to me.

To fix this, you should not subscribe to BeginRequest directly; instead, create a Task-returning "handler", wrap it in EventHandlerTaskAsyncHelper, and pass it to AddOnBeginRequestAsync.

Something like this:

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".
}

and to subscribe:

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


来源:https://stackoverflow.com/questions/17863503/asynchronous-httpmodule-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!