How to get the OWIN context on ASP.Net Identity?

asp.net-identity-2 asp.net-mvc entity-framework

Question

I'm trying to get the DbContext from the current Owin context, so I can use a single context on my application, however, I'm getting a NullReferenceException.

I can access UserManager and RoleManager:

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

They're configured how they came by default in the Identity sample project:

app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

But trying to get the context to use it directly:

ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();

It always returns null on my controller. How can I get the current DbContext from the Owin context?

EDIT:

I was creating a new context to use with my generic repository

public AdminController()
    {
        AppContext = new ApplicationDbContext();
        this.repoProyects = new GenericRepository<Proyect>(AppContext);
    }

But it was creating a problem with entities being referenced from multiple contexts, so I'm trying to get the current Owin context like this:

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

HttpContext is always null from here, so I don't know how to get the context to pass it to my class.

1
5
11/2/2014 2:04:21 AM

Popular Answer

I was missing the initialization of my entities in the Startup method ConfigureOauth...

app.CreatePerOwinContext<OwinAuthDbContext>(() => new OwinAuthDbContext());  

Found the answer here: http://www.c-sharpcorner.com/UploadFile/ff2f08/token-based-authentication-using-Asp-Net-web-api-owin-and-i/

0
4/21/2016 8:30:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow