【问题标题】:The CreateAsync method neither throws an error nor updates the databaseCreateAsync 方法既不抛出错误也不更新数据库
【发布时间】:2019-09-22 01:59:54
【问题描述】:

我有以下简单的代码来使用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 接口调用的。

【问题讨论】:

  • 您是否确认它正在更新正确的数据库?您是否对代码进行了概要分析? result 的其他属性是否有帮助?您是否在附加调试器的情况下逐行执行代码以确保它甚至被命中?有没有调用你的 Create 方法的代码?
  • @mason 它停在IdentityResult result 行中。但是,虽然有断点,但后来并没有停止。还有step into调试选项不访问CreateAsync里面。
  • 你可能遇到了死锁,你怎么称呼它?
  • @nalnpir 我在 OP 中分享了它。
  • 您是否尝试将 ConfigureAwait(false) 添加到 CreateAsync?老实说,我不确定这是否会起作用,因为您的公共方法是同步的,我认为它会在执行任何操作之前返回,这就是您的代码根本没有执行的原因

标签: c# asp.net asp.net-core async-await asp.net-identity


【解决方案1】:

您从未等待异步调用。因此,当您的操作结果返回时,它甚至可能还没有完成,因此可能永远不会运行。确保您等待任何异步调用。这意味着调用方法需要标记为异步(并使其返回任务或任务),一直到调用堆栈,直到它到达事件处理程序或框架代码。你的代码应该是这样的:

[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 });
    }   
}

另请注意,将异常详细信息返回给客户端用户是个坏主意。异常可能包含攻击者可以用来利用您的系统的敏感信息。相反,只需返回一个通用的“抱歉,出现问题”消息并将异常详细信息记录到您的日志框架。如果您没有日志框架,请获取一个。

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多