CreateAsync 方法既不抛出错误也不更新数据库

The CreateAsync method neither throws an error nor updates the database

我有以下使用 CreateAsync 方法创建新用户的简单代码。该代码不会抛出任何错误,但也不会更新数据库。我在 IdentityResult result 行添加了一个断点,它停止的地方,另一个在 if 语句中,它不停止的地方。结果,我不知道如何调试这段代码并找到错误。有帮助吗?

public async Task<IdentityResult> Create(ApplicationUser user, string password)
{
    IdentityResult result = await _userManager.CreateAsync(user, password);

    if (!result.Succeeded)
    {
        throw new AppException("Failed");
    }

    return result;
}

Create 函数是从控制器调用的:

[AllowAnonymous]
[HttpPost]
[Route("api/ApplicationUser/Register")]
public IActionResult Register([FromBody]ApplicationUserDto userDto)
{
    //map dto to entity
    var user = _mapper.Map<ApplicationUser>(userDto);

    try
    {
        // save 
        _userService.Create(user, userDto.Password);
        return Ok();
    }
    catch (AppException ex)
    {
        // return error message if there was an exception
        return BadRequest(new { message = ex.Message });
    }   
}

Register 方法是从 React 接口调用的。

您从未等待您的异步调用。因此,它甚至可能在您的操作结果 return 之前完成,因此可能永远不会得到 运行。确保您等待任何异步调用。这意味着调用方法需要标记为异步(并使 return 一个任务或任务),一直向上调用堆栈,直到它到达事件处理程序或框架代码。您的代码应如下所示:

[AllowAnonymous]
[HttpPost]
[Route("api/ApplicationUser/Register")]
public async Task<IActionResult> Register([FromBody]ApplicationUserDto userDto)
{
    //map dto to entity
    var user = _mapper.Map<ApplicationUser>(userDto);

    try
    {
        // save 
        await _userService.Create(user, userDto.Password);
        return Ok();
    }
    catch (AppException ex)
    {
        // return error message if there was an exception
        return BadRequest(new { message = ex.Message });
    }   
}

另请注意,向客户端用户 return 异常详细信息是个坏主意。异常可能包含敏感信息,攻击者可以利用这些信息来攻击您的系统。相反,只需 return 一条通用 "Sorry, something went wrong" 消息并将异常详细信息记录到您的日志记录框架。如果您没有日志记录框架,请获取一个。