2013-07-25 6 views
5

次のコードを含む同期HttpModuleがあります。私は空のMVC4アプリケーション(NET 4.5)からモジュールを実行しようとすると、私は次のエラーを取得する 非同期HttpModule MVC

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

この時点で非同期操作を開始することはできません。非同期 操作は、非同期ハンドラまたは モジュール内、またはページライフサイクルの特定のイベント中にのみ開始できます。ページの実行中に 例外が発生した場合は、ページが<%@ Page Async = "true"%>と示された であることを確認してください。

実際にはエラーが発生してはいけないと私は思っていました。

私は周りに掘り出し物を持っていましたが、私は何か助けを見つけることができないようです、誰にもアイデアはありますか?

答えて

10

したがって、同期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); 
+0

これは、あなたが今私を助けてきた数回でなければならない、ありがとう! 私は申し訳ありませんが、コードは実際にNet 4.0で書かれており、4.0と4.5の両方をサポートできるように、asyncキーワードをサポートするためにBCLライブラリを使用しています。したがって、私はEventHandlerTaskAsyncHelperを使用できません。 –

+2

残念ながら、 'Microsoft.Bcl.Async'には[ASP.NET 4.0で未定義の動作]があります(http://blogs.msdn.com/b/webdev/archive/2012/11/19/all-about-httpruntime -targetframework.aspx)。 ASP.NETでは、.NET 4.0ではなく.NET 4.5で実行する必要があります。 –

+0

Ah ok ... web.configの ' 'ノードから' targetFramework = "4.5" 'を削除するとこれをテストします。これはうまくいきます。つまり、NET 4.0ではhttpModuleは非同期ではありませんか?これはMVCで 'EventHandlerTaskAsyncHelper'を使わずに非同期httpモジュールを使うことができないということですか、それとも別の方法です。私はまだそれが正直であるとエラーを投げている混乱している陰です。メッセージは、httpModulesが正常であると言うようです。 –