Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 508
Carlos Martinez Avatar asked Nov 09 '22 23:11

Carlos Martinez


1 Answers

I had the same issue using Identity Framework when I added some extra navigation properties to the ApplicationUser. If you set

appContext = HttpContext.Current.GetOwinContext().Get<ApplicationDbContext>();

in OnActionExecuting instead of in the constructor, then OWIN should be ready to return the DbContext that's in use at that point. OnActionExecuting kicks in before any action methods fire, so this should be early enough to be useful. Hope that helps.

like image 162
diego Avatar answered Nov 15 '22 05:11

diego