2014-09-10 152 views
12

隨着獲取當前OwinContext不使用的HttpContext

HttpContext.Current.GetOwinContext() 

我可以在Web應用程序收到當前OwinContext。

With OwinContext.Set<T> and OwinContext.Get<T>我存儲了整個請求應存在的值。

現在我有一個組件應該在web和控制檯owin應用程序中使用。在這個組件中,我目前無法訪問http上下文。

在我使用線程和異步功能的應用程序。

我也嘗試過使用CallContext,但這似乎在某些情況下會丟失數據。

那麼我如何訪問當前的OwinContext?還是有其他的背景下我可以發揮我的價值觀?

回答

4

我使用WebApi AuthorizationFilter執行以下操作,如果您有中間件來支持它,例如app.UseWebApi(app)for WebApi,您也應該可以在MVC控制器和WebApi控制器上下文中執行此操作。

該組件必須支持Owin管道,否則不知道如何從正確的線程獲取上下文。

因此,也許你可以創建自己的自定義

OwinMiddleware

在你Owin啓動wireup使用app.Use()這個組件。

更多信息here

我的屬性中間件

public class PropertiesMiddleware : OwinMiddleware 
{ 
    Dictionary<string, object> _properties = null; 

    public PropertiesMiddleware(OwinMiddleware next, Dictionary<string, object> properties) 
     : base(next) 
    { 
     _properties = properties; 
    } 

    public async override Task Invoke(IOwinContext context) 
    { 
     if (_properties != null) 
     { 
      foreach (var prop in _properties) 
       if (context.Get<object>(prop.Key) == null) 
       { 
        context.Set<object>(prop.Key, prop.Value); 
       } 
     } 

     await Next.Invoke(context); 
    } 
} 

Owin啓動配置

public void Configuration(IAppBuilder app) 
{ 

     var properties = new Dictionary<string, object>(); 
     properties.Add("AppName", AppName); 

     //pass any properties through the Owin context Environment 
     app.Use(typeof(PropertiesMiddleware), new object[] { properties }); 
} 

的WebAPI過濾

public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext context, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) 
{ 

     var owinContext = context.Request.GetOwinContext(); 
     var owinEnvVars = owinContext.Environment; 
     var appName = owinEnvVars["AppName"]; 
} 

快樂編碼!