加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 异步HttpModule MVC

发布时间:2020-12-15 19:00:57 所属栏目:asp.Net 来源:网络整理
导读:我有一个包含以下代码的同步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 na
我有一个包含以下代码的同步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)运行该模块时,我收到以下错误.

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

我似乎错过了一些东西但是通过我的阅读,错误实际上不应该发生.

我有一个挖掘,但我似乎无法找到任何帮助,有没有人有任何想法?

解决方法

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

要解决此问题,您不应直接订阅BeginRequest;相反,创建一个返回任务的“处理程序”,将其包装在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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读