我正在使用仅使用用户名和密码的 ASP.NET Core Identity 实现一个简单的身份验证系统。当我调用 Register 操作时,我收到标题中提到的错误。
在与注册关联的代码下方。
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("Default")));
services.AddIdentity<IdentityUser,
IdentityRole().AddEntityFrameworkStores<AppDbContext>();`
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
}
AccountController.cs:
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<IActionResult> Register(RegistrationViewModel registrationViewModel)
{
if (ModelState.IsValid)
{
var user = new IdentityUser {UserName = registrationViewModel.UserName};
var result = await _userManager.CreateAsync(user, registrationViewModel.Password);
if (result.Succeeded)
return RedirectToAction("Index", "Home");
var errors = result.Errors;
var message = string.Join(", ", errors);
ModelState.AddModelError("", message);
}
return View(registrationViewModel);
}
RegistrationViewModel.cs:
public class RegistrationViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
Registerm.cshtml:
@model RegistrationViewModel
<form asp-controller="Account" asp-action="Register" method="post" class="form-horizontal" role="form">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Password" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-primary" value="Register" />
</div>
</div>
`
据我所知,当登录名已经与帐户相关联时会发生这种错误,但是应该存储所有用户数据的表是空的。
最佳答案
尝试使用它来获得更好的错误消息。您的 toString on Errors 只是返回对象类型而不是其中的内容。
var message = string.Join(", ", response.Errors.Select(x => "Code " + x.Code + " Description" + x.Description));
关于c# - 尝试注册时出现 Microsoft.AspNetCore.Identity.IdentityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298598/