【问题标题】:Edit Custom UserIdentity objects (in database)编辑自定义 UserIdentity 对象(在数据库中)
【发布时间】:2020-07-25 14:57:51
【问题描述】:
我正在使用 ASP.NET Identity 制作我的第一个 ASP.NET Core 应用程序。我现在设法创建了一个自定义的IdentityUser 类(命名为ApplicationUser),它从脚手架 Identity 包中提供的标准 IdentityUser 类扩展而来。 ApplicationUser 现在有一些额外的字段(地址、状态、名字、姓氏),我的应用程序和数据库以所需的方式识别两者,并且在使用注册表单时新用户被正确添加到数据库中。自然我把IdentityUser的用法换成了ApplicationUser,自定义了
Register.cshtml
和
注册.cshtml.cs
,以便使用额外的字段。
我现在的问题是,我觉得我不知道应该如何在“自然意义上”更新用户对象(在数据库中)。默认UserManager 似乎旨在更新默认IdentityUser 的实例,但不是从IdentityUser 继承的类。似乎UserManager 默认处理异步操作等问题,而我怀疑有任何用途的唯一(默认)可用方法是UserManager 中的#UpdateAsync。
我能做什么?
【问题讨论】:
标签:
asp.net-mvc
asp.net-core
.net-core
【解决方案1】:
这是一个关于如何更新 ApplicationUser 的工作演示:
型号:
public class ApplicationUser:IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
查看:
@model ApplicationUser
<form asp-action="UpdateUser">
<div>
<label asp-for="Email"></label>
<input asp-for="Email" />
</div>
<div>
<label asp-for="FirstName"></label>
<input asp-for="FirstName" />
</div>
<div>
<label asp-for="LastName"></label>
<input asp-for="LastName" />
</div>
<input type="submit" value="update" />
</form>
控制器:
public class HomeController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpPost]
public IActionResult UpdateUser(ApplicationUser applicationUser)
{
var user = _userManager.FindByEmailAsync(applicationUser.Email).Result;
//modify the data...
user.FirstName = applicationUser.FirstName;
user.LastName = applicationUser.LastName;
var result = _userManager.UpdateAsync(user).Result;
return RedirectToAction("Index");
}
}
ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
【解决方案2】:
UserManager 与继承自 IdentityUser 的泛型类型一起使用,您已经这样做了。因此,只需将 UserManager<ApplicationUser> 而不是 UserManager<IdentityUser> 注入您需要它的位置(例如 Register.cshtml.cs)并使用它来对您的用户进行操作。