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,你好,我更新了示例代碼。 – Shrike

+0

@ShrikeMay我建議讓你的代碼更通用? – user843681