5

Web APIアプリケーションでは、Castle Windsorを使用してPerWebRequestの有効期間で構成されたサービスを提供し、すべてIIS上で正常に動作します。HttpRequestMessage.Propertiesを使用して要求ごとにコンテキストを運ぶ

しかし、私はASP.NET Web APIの自己ホスト(ベータ版)を使用する場合package私は、HTTP要求ごとにこれらのサービスをスコープするために、カスタムライフタイムを作成する必要があります。

HttpRequestMessage.Propertiesを使用してリクエストごとのコンテキストを伝達するにはどうすればよいですか?

答えて

8

私はHttpRequestMessage.Propertyにいくつかのあなたのオブジェクトを設定するには、メッセージ・ハンドラを使用して、あなたをお勧め:

public class MyApplication : HttpApplication 
{ 
    protected void Application_Start() 
    { 
     RegisterHttpMessageHandlers(GlobalConfiguration.Configuration); 
    } 
    public void RegisterHttpMessageHandlers(HttpConfiguration config) 
    { 
     config.MessageHandlers.Add(new MyMessageHandler()); 
    } 
} 

public static class MyHttpMessageHandlerExtensions 
{ 
    public static class HttpPropertyKey 
    { 
     public static readonly string MyProperty = "MyCompany_MyProperty"; 
    } 

    public static MyContext GetContext(this HttpRequestMessage request) 
    { 
     return (MyContext)request.Properties[HttpPropertyKey.MyProperty ]; 
    } 

    public static void SetContext(this HttpRequestMessage request, MyContext ctx) 
    { 
     request.Properties[HttpPropertyKey.MyProperty] = ctx; 
    } 
} 
public class MyMessageHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     request.SetContext(new MyContext(){/*some your data*/}); 
     return base.SendAsync(request, cancellationToken); 
    } 
} 

public class MyController: ApiController 
{ 
    public object GetData() 
    { 
     MyContext ctx = this.Request.GetContext(); // the extenstion method is used 
    } 
} 
+1

あなたが実際にあなたのAPI呼び出しの後の文脈を読み取る方法に言及することはありません。 – BradLaney

+1

@BradLaney、yor're、サンプルコードを更新しました。 – Shrike

+0

@ShrikeMayコードをより一般的にすることをお勧めしますか? – user843681

関連する問題