我在尝试创建异步用户时遇到错误。
var create = await _userManager.CreateAsync(user, model.Password);
我可以在IdentityResult
上访问一个名为 errors
的属性。但是我无法弄清楚如何访问它。知道我如何捕获它以便我可以看到它出错了什么吗?
我在下面发布了完整的控制器代码。出于某种原因,每当我尝试用我的 var 创建做任何事情时,它都会忽略它。我什至不能踏入它。
namespace TechsportiseOnline.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class RegistrationController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IConfiguration _configuration;
private readonly IOptions<JWTSettings> _jwtConfig;
private readonly IEmailSender _emailSender;
public RegistrationController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IConfiguration configuration,
IOptions<JWTSettings> jwtConfig,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
_jwtConfig = jwtConfig;
_emailSender = emailSender;
}
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
MobileNumber = model.MobileNumber,
Marketing = model.Marketing,
Newsletter = model.Newsletter
};
var result = new CreateUserResult();
var create = await _userManager.CreateAsync(user, model.Password);
if (create.Succeeded == true)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code.ToString(), Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
//await _createContact.CreateContactAsync(model.Email, model.FirstName, model.LastName, model.Marketing, model.Newsletter);
var fields = new Dictionary<string, string>();
fields.Add("firstname", model.FirstName);
fields.Add("lastname", model.LastName);
fields.Add("newsletter", model.Newsletter.ToString());
fields.Add("marketing", model.Marketing.ToString());
string publicaccountid = "55ebcc8b-b23f-4843-9dcb-1df08811de65";
var createcontact = ElasticEmailClient.Api.Contact.AddAsync(publicAccountID: publicaccountid, email: model.Email, field: fields);
//await _signInManager.SignInAsync(user, isPersistent: false);
return CreatedAtRoute("CreateAccount", model);
}
else
{
return BadRequest("Could not register account");
}
}
else
{
return BadRequest("The model is invalid");
}
}
}
}
这是我的示例代码: 我正在使用 MediatR 来(尝试)分离查询和命令。
CreateUserByAdminHandler
public class CreateUserByAdminHandler : IAsyncRequestHandler<CreateUserByAdmin, CreateUserResult>
{
private readonly UserManager<AppUser> _userManager;
public CreateUserByAdminHandler(UserManager<AppUser> userManager)
{
_userManager = userManager;
}
public async Task<CreateUserResult> Handle(CreateUserByAdmin command)
{
var result = new CreateUserResult();
try
{
var appUser = new AppUser
{
UserName = command.Username.Trim(),
FirstName = command.FirstName.Trim(),
LastName = command.LastName.Trim(),
Email = command.Email,
PhoneNumber = command.PhoneNumber,
Status = UserStatus.Active
};
var createResult = await _userManager.CreateAsync(appUser, command.Password);
if (!createResult.Succeeded)
{
// IdentityResult has Errors property, which is a list of
// IdentityError. IdentityError has Code and Description
// property. It's up to you to select whichever property
// for the error message.
result.AddErrors(createResult.Errors.Select(ier => ier.Description));
return result;
}
result.NewUser = appUser;
}
catch (Exception ex)
{
result.SetException(ex);
}
return result;
}
}
将断点设置为 if (创建.成功 == true) 并检查创建对象或添加 else 语句以读取错误。这是我用来记录错误的代码。
var result = await _userManager.CreateAsync(newUser, "Password123!");
if (result.Succeeded)
{
//do stuff
}
foreach (var error in result.Errors)
{
_logger.LogWarning("Code: " + error.Code + " " + error.Description);
}