asp.net-mvc 在 AccountController 之外访问 UserManager
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29292582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing UserManager outside AccountController
提问by Spionred
I am trying to set the value of a column in aspnetusertable from a different controller (not accountcontroller). I have been trying to access UserManagerbut I can't figure our how to do it.
我正在尝试aspnetuser从不同的控制器(不是accountcontroller)设置表中列的值。我一直在尝试访问,UserManager但我不知道该怎么做。
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 UserManagerhas not been instantiated the controller)
这不会编译(我认为是因为UserManager尚未实例化控制器)
I also tried to create a public method in the AccountControllerto accept the value I want to change the value to and do it there but I can't figure out how to call it.
我还尝试在中创建一个公共方法AccountController来接受我想将值更改为的值并在那里执行,但我不知道如何调用它。
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:
我尝试在另一个控制器中实例化 UserManager ,如下所示:
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:
更新 2:
I have moved the function to the IdentityModel (don't ask I am clutching at straws here) like so:
我已经将函数移到 IdentityModel (不要问我在这里抓着稻草)像这样:
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:
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).
我在这里做错了什么?感觉就像我完全在错误的树上吠叫。我想要做的就是从不同控制器(即不是 AccountsController)的操作更新 aspnetuser 表中的列。
回答by Iravanchi
If you're using the default project template, the UserManagergets created the following way:
如果您使用的是默认项目模板,则会通过UserManager以下方式创建:
In the Startup.Auth.cs file, there's a line like this:
在 Startup.Auth.cs 文件中,有这样一行:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
that makes OWIN pipeline instantiate an instance of ApplicationUserManagereach time a request arrives at the server. You can get that instance from OWIN pipeline using the following code inside a controller:
这使得 OWIN 管道在ApplicationUserManager每次请求到达服务器时实例化一个实例。您可以使用控制器内的以下代码从 OWIN 管道获取该实例:
Request.GetOwinContext().GetUserManager<ApplicationUserManager>()
If you look carefully at your AccountControllerclass, you'll see the following pieces of code that makes access to the ApplicationUserManagerpossible:
如果你仔细查看你的AccountController类,你会看到以下代码片段可以访问ApplicationUserManager:
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 ApplicationUserManagerclass, you need to use the ApplicationUserManager.Createstatic method so that you have the appropriate settings and configuration applied to it.
请注意,如果您需要实例化ApplicationUserManager该类,则需要使用ApplicationUserManager.Create静态方法,以便对其应用适当的设置和配置。
回答by Muhmmad Abubakar Ikram
If you have to get UserManager's instance in another Controllerjust add its parameter in Controller's constructor like this
如果您必须在另一个控制器中获取 UserManager 的实例,只需像这样在控制器的构造函数中添加其参数
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 !
但是我必须在一个不是控制器的类中获取 UserManager !
Any help would be appreciated.
任何帮助,将不胜感激。
UPDATE
更新
I am considering you are using asp.net core
我正在考虑您正在使用 asp.net 核心
回答by Ganesh Todkar
FOR MVC 5
对于 MVC 5
The steps to access usermanger or createUser outside Account controller is easy. Follow the below steps
在帐户控制器之外访问 usermanger 或 createUser 的步骤很简单。请按照以下步骤操作
- Create a controller, consider SuperAdminController
Decorate the SuperAdminController same as the AccountController as below,
private readonly IAdminOrganizationService _organizationService; private readonly ICommonService _commonService; private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public SuperAdminController() { } public SuperAdminController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public SuperAdminController(IAdminOrganizationService organizationService, ICommonService commonService) { if (organizationService == null) throw new ArgumentNullException("organizationService"); if (commonService == null) throw new ArgumentNullException("commonService"); _organizationService = organizationService; _commonService = commonService; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } }Create User in Action method
[HttpPost] public async Task<ActionResult> AddNewOrganizationAdminUser(UserViewModel userViewModel) { if (!ModelState.IsValid) { return View(userViewModel); } var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email }; var result = await UserManager.CreateAsync(user, userViewModel.Password); if (result.Succeeded) { var model = Mapper.Map<UserViewModel, tblUser>(userViewModel); var success = _organizationService.AddNewOrganizationAdminUser(model); return RedirectToAction("OrganizationAdminUsers", "SuperAdmin"); } AddErrors(result); return View(userViewModel); }
- 创建一个控制器,考虑 SuperAdminController
如下装饰与 AccountController 相同的 SuperAdminController,
private readonly IAdminOrganizationService _organizationService; private readonly ICommonService _commonService; private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public SuperAdminController() { } public SuperAdminController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public SuperAdminController(IAdminOrganizationService organizationService, ICommonService commonService) { if (organizationService == null) throw new ArgumentNullException("organizationService"); if (commonService == null) throw new ArgumentNullException("commonService"); _organizationService = organizationService; _commonService = commonService; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } }创建用户操作方法
[HttpPost] public async Task<ActionResult> AddNewOrganizationAdminUser(UserViewModel userViewModel) { if (!ModelState.IsValid) { return View(userViewModel); } var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email }; var result = await UserManager.CreateAsync(user, userViewModel.Password); if (result.Succeeded) { var model = Mapper.Map<UserViewModel, tblUser>(userViewModel); var success = _organizationService.AddNewOrganizationAdminUser(model); return RedirectToAction("OrganizationAdminUsers", "SuperAdmin"); } AddErrors(result); return View(userViewModel); }
回答by Mitch Stewart
I ran into this same problem and modified my code to pass a reference to the UserManager class from the Controller to the Model:
我遇到了同样的问题并修改了我的代码,将 UserManager 类的引用从 Controller 传递到 Model:
//snippet from Controller
public async Task<JsonResult> UpdateUser(ApplicationUser applicationUser)
{
return Json(await UserIdentityDataAccess.UpdateUser(UserManager, applicationUser));
}
//snippet from Data Model
public static async Task<IdentityResult> UpdateUser(ApplicationUserManager userManager, ApplicationUser applicationUser)
{
applicationUser.UserName = applicationUser.Email;
var result = await userManager.UpdateAsync(applicationUser);
return result;
}

