.NET Core 2标识CreateAsync错误捕获

时间:2017-10-18 14:37:46

标签: c# asp.net-identity asp.net-core-2.0

尝试CreateAsync用户时收到错误。

var create = await _userManager.CreateAsync(user, model.Password);

我可以在名为IdentityResult的{​​{1}}上访问一个属性。但是我无法弄清楚如何访问它。任何想法我怎么能抓住它所以我可以看到它是错误的?

我在下面发布了完整的控制器代码。出于某种原因,每当我尝试使用我的var创建它时,它就会忽略它。我甚至无法介入它。

errors

2 个答案:

答案 0 :(得分:0)

这是我的示例代码:我使用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;
    }
}

答案 1 :(得分:0)

if(create.Succeeded == true)上设置断点,并检查create对象或添加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);
}