Accessing UserManager outside AccountController
Solution 1
If you're using the default project template, the UserManager
gets created the following way:
In the Startup.Auth.cs file, there's a line like this:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
that makes OWIN pipeline instantiate an instance of ApplicationUserManager
each time a request arrives at the server. You can get that instance from OWIN pipeline using the following code inside a controller:
Request.GetOwinContext().GetUserManager<ApplicationUserManager>()
If you look carefully at your AccountController
class, you'll see the following pieces of code that makes access to the ApplicationUserManager
possible:
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
Please note, that in case you need to instantiate the ApplicationUserManager
class, you need to use the ApplicationUserManager.Create
static method so that you have the appropriate settings and configuration applied to it.
Solution 2
If you have to get UserManager's instance in another Controller just add its parameter in Controller's constructor like this
public class MyController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;;
}
}
But I have to get UserManager in a class that is not controller !
Any help would be appreciated.
UPDATE
I am considering you are using asp.net core
Comments
-
Spionred almost 2 years
I am trying to set the value of a column in
aspnetuser
table from a different controller (notaccountcontroller
). I have been trying to accessUserManager
but I can't figure our how to do it.So far I have tried the following in the controller I want to use it in:
ApplicationUser u = UserManager.FindById(User.Identity.GetUserId()); u.IsRegComplete = true; UserManager.Update(u);
This would not compile (I think because
UserManager
has not been instantiated the controller)I also tried to create a public method in the
AccountController
to accept the value I want to change the value to and do it there but I can't figure out how to call it.public void setIsRegComplete(Boolean setValue) { ApplicationUser u = UserManager.FindById(User.Identity.GetUserId()); u.IsRegComplete = setValue; UserManager.Update(u); return; }
How do you access and edit user data outside of the Account Controller?
UPDATE:
I tried to instantiate the UserManager in the other controller like so:
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); ApplicationUser u = userManager.FindById(User.Identity.GetUserId());
I the project complied (got a little excited) but when I ran the code I get the following error:
Additional information: The entity type ApplicationUser is not part of the model for the current context.
UPDATE 2:
I have moved the function to the IdentityModel (don't ask I am clutching at straws here) like so:
public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } public Boolean IsRegComplete { get; set; } public void SetIsRegComplete(string userId, Boolean valueToSet) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>()); ApplicationUser u = new ApplicationUser(); u = userManager.FindById(userId); u.IsRegComplete = valueToSet; return; } }
However I am still getting the following:
The entity type ApplicationUser is not part of the model for the current context.
There is also the following class in IdentitiesModels.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
What am I doing wrong here? It feels like I am completely barking up the wrong tree. All I am trying to do is update a column in aspnetuser table from the action of a different controller (i.e not the AccountsController).
-
Iravanchi about 9 yearsIt seems from the error message like the "db" you're passing to the store, is not the same DbContext that contains your Identity tables.
-
Mike Debela about 9 yearsdo you have
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{}
in yourdb
context class? -
Spionred about 9 yearsSee updated post above - thanks
-
Mike Debela about 9 years
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
-
Spionred about 9 yearsYup, That worked a treat. Thank you!
-
salli over 7 yearsI don't have enough rep yet to comment, so I am making a new an answer post. Just to add to @Iravanchi answer the extension method for GetOwinContext() has been moved to Microsoft.AspNet.Identity.Owin; stackoverflow.com/questions/23532964/…
-
-
Spionred about 9 yearsThanks for the contribution. The suggestion in the comment above worked. I kept the code in the IdentityModels.cs file as I will need to access it in multiple places.
-
Iravanchi about 9 yearsI suggest that you retrieve the
UserManager
from OWIN context instead of creating a new instance, as it is created in each request anyway, and creating a new one is redundant overhead. -
rollsch over 7 yearsBut how to you pass it to your controller in the first place? I have no references to my controller in my entire project, so I don't know how to pass it a reference to the userManager? Where is it actually instantiated?
-
Muhmmad Abubakar Ikram over 7 yearsNo no. UserManager<ApplicationUser> will be injected to your application controllers from your startup.cs class. Make an ASP.NET Identity project in ASP.NET Core and see the startup.cs class. The following code is injecting UserManager<Application> Instance to your controllers services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
-
rollsch over 7 yearsSo I see, lots of magic going on. Hard to follow when all the code that does this stuff is hidden away.
-
Jonathan Wood about 7 yearsIf I try this, I get an error that the controller has no default constructor.
-
Muhmmad Abubakar Ikram about 7 years@JonathanWood try to make another constructor with empty parameters then chek
-
Jonathan Wood about 7 years@ДвυΒдкдя: Yes, of course. But then I don't have a
UserManager<ApplicationUser>
instance. -
Muhmmad Abubakar Ikram about 7 years@JonathanWood create a new asp.net core application with user authentication and see AccountController