2016-08-14 22 views
2

我有一种情况,突然我的HttpContext通过类库访问它时为null。作为帮助程序的类库包含一种读取信息并将其返回的方法。HttpContext null,codepath需要不同的线程

深入挖掘后,我发现代码正在另一个线程上执行,我假设HttpContext绑定到特定的线程。在控制器中,HttpContext是可用的,但是当我从类库访问HttpContext时,它变成了null,并且出现在另一个线程中。

我真的想知道为什么会发生这种情况/我如何找到这种行为的根源?

当我在GetTenantSession()上放置一个调试点时,发生UserManager.Find执行的那一刻,我可以看到线程已更改,并且HttpContext为空。

我的控制器(带T,A,B,C用于调试)

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public ActionResult Index(LoginViewModel model, string returnUrl) 
{ 
    if (!ModelState.IsValid) 
    return View(model); 

    var t = Thread.CurrentThread.ManagedThreadId; 
    var a = (IDocumentSession)HttpContext.Items["RavenDB_TenantSession"]; 
    var b = (IDocumentSession)System.Web.HttpContext.Current.Items["RavenDB_TenantSession"]; 
    var c = RavenContext.GetTenantSession(); 

    var user = UserManager.Find(model.Email, model.Password); 

    return View(); 
} 

RavenContext.cs(类库)

public class RavenContext 
{ 
    public static IDocumentSession GetMasterSession() 
     { 
      return (IDocumentSession)HttpContext.Current.Items["RavenDB_MasterSession"]; 
     }  
     public static IDocumentSession GetTenantSession() 
     { 
      var t = Thread.CurrentThread.ManagedThreadId;    
      return (IDocumentSession)HttpContext.Current.Items["RavenDB_TenantSession"]; 
     } 
     public static void InitTenantSession(string tenantDBName) 
     { 
      HttpContext.Current.Items["RavenDB_TenantSession"] = GetDocumentStore().OpenSession(tenantDBName); 
     } 
     public static IDocumentStore GetDocumentStore() 
     { 
      return (IDocumentStore)HttpContext.Current.Items["RavenDB_DocumentStore"]; 
     } 
} 

的UserManager,引用RavenContext.GetTenantSession

public class UserManager : UserManager<User> 
    { 
     public UserManager(IUserStore<User> store) : base(store){} 

     public static UserManager Create(IdentityFactoryOptions<UserManager> options, IOwinContext context) 
     { 
      var userStore = new UserStore<User>(RavenContext.GetTenantSession); 

回答

0

也许你的例子中缺少一些代码。您可能会在不同的线程上调用 UserManager.Create(),可能位于App.Startup, ,其中HttpContext不存在。 (因为它只存在于服务器 - 客户端之间的会话中)。