如何在ASP.Net Identity上获取OWIN上下文?

Car*_*nez 5 asp.net-mvc entity-framework asp.net-identity-2

我正在尝试从当前的Owin上下文中获取DbContext,因此我可以在我的应用程序上使用单个上下文,但是,我得到一个NullReferenceException.

我可以访问UserManager和RoleManager:

private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

他们在Identity示例项目中默认配置了它们的来源:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Run Code Online (Sandbox Code Playgroud)

但是试图让上下文直接使用它:

ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

它总是在我的控制器上返回null.如何从Owin上下文中获取当前的DbContext?

编辑:

我正在创建一个与我的通用存储库一起使用的新上下文

public AdminController()
    {
        AppContext = new ApplicationDbContext();
        this.repoProyects = new GenericRepository<Proyect>(AppContext);
    }
Run Code Online (Sandbox Code Playgroud)

但是它创建了一个问题,实体是从多个上下文引用的,所以我试图得到当前的Owin上下文:

public AdminController()
    {
        this.AppContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        this.repoProyects = new GenericRepository<Proyect>(AppContext);
    }
Run Code Online (Sandbox Code Playgroud)

HttpContext从这里始终为null,所以我不知道如何让上下文将它传递给我的类.

小智 1

当我向 ApplicationUser 添加一些额外的导航属性时,我在使用身份框架时遇到了同样的问题。如果你设置

appContext = HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

在 OnActionExecuting 中而不是在构造函数中,那么 OWIN 应该准备好返回此时正在使用的 DbContext。OnActionExecuting 在任何操作方法触发之前启动,因此这应该足够早以发挥作用。希望有帮助。