CreateAsync 不会使用派生的 IdentityUser 将 IdentityUser 保存到数据库

CreateAsync doesn't save IdentityUser to database with derived IdentityUser

当发布以下代码时,在它到达 _userManager.CreateAsync 方法之前工作正常。没有数据保存到数据库中。

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly ApplicationDbContext _appDbContext;

    private readonly UserManager<IdentityUser> _userManager;

    public ValuesController(UserManager<IdentityUser> userManager, ApplicationDbContext appDbContext)
    {
        _userManager = userManager;
        _appDbContext = appDbContext;
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        AppUser user = new AppUser();
        user.Email = "email@mail.co.uk";
        user.FirstName = "mark";
        user.LastName = "Macneill";
        user.UserName = "Saints22";
        await _userManager.CreateAsync(user, "P4$$word");

        return new OkObjectResult("Account created");

    }

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

谢谢neville-nazerane

我在依赖注入中有 IdentityUser,我所要做的就是将 IdentityUser 更改为 AppUser。

Startup.cs

services.AddIdentity<AppUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

您似乎没有直接使用 IdentityUser,而是 AppUser class。这可能是 class 扩展 IdentityUser<>IdentityUser。我不确定你的其余设置是否正确,所以这是过程:

如果您创建了自定义 AppUser class,假设您是按如下方式创建的:

class AppUser : IdentityUser<int>

这意味着您已经像 int 中那样分配了主键。但是,如果您改为扩展 IdentityUser,请注意 IdentityUser 扩展了 IdentityUser<string>,这意味着您的密钥是一个字符串。继续,我假设您的密钥是 int。如果没有,您可以进行相应的更改(将所有 int 更改为您的密钥类型。

在您的启动 class 中,您需要添加以下内容以将此注册为您的用户 class 用于身份

services.AddIdentity<AppUser, IdentityRole<int>>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

你的ApplicationDbContext需要定义如下:

public class ApplicationDbContext : IdentityDbContext<AppUser, IdentityRole<int>, int>

如果不想在上面两段代码中使用IdentityRole<int>,可以定义一个自定义角色class,如下:

public AppUserRole : IdentityRole<int>

完成这些设置后,您需要注入 UserManager<AppUser> 而不是 UserManager<IdentityUser>