ASP.Net Web API存储库更新错误500

时间:2018-01-11 19:32:07

标签: c# asp.net-core-webapi

我的Web Api控制器有一个UpdateArea方法,传递id并在正文中传递更新的值。它写成如下:

[HttpPut("{id}")]
public async Task<IActionResult> UpdateArea(Guid id, [FromBody] AreaForUpdateDto areaForUpdateDto)
{
    // Check that the 'area' object parameter can be de-serialised to a AreaForUpdateDto.
    if (areaForUpdateDto == null)
    {
        _logger.LogError("AreasController.UpdateArea failed: Could not map area object parameter to a AreaForUpdateDto");

        // Return an error 400.
        return BadRequest();
    }

    // Ensure that the Area exists.
    var areaEntityFromRepo = _areaRepository.GetArea(id);

    // Map(source object (Dto), destination object (Entity))
    Mapper.Map(areaForUpdateDto, areaEntityFromRepo);
    _areaRepository.UpdateArea(areaEntityFromRepo);

    // Save the updated Area entity, added to the DbContext, to the SQL database.
    if (await _areaRepository.SaveChangesAsync())
    {
        var areaFromRepo = _areaRepository.GetArea(id);
        if (areaFromRepo == null)
            return NotFound();

        var area = Mapper.Map<AreaDto>(areaFromRepo);
        return Ok(area);
    }

    // The save has failed.
    _logger.LogWarning($"Updating Area {id} failed on save.");
    throw new Exception($"Updating Area {id} failed on save.");
}

这可以正常工作,直到我的应用程序要求更新,但请求的主体与数据库中的现有数据相同。发生这种情况时,_areaRepository.SaveChangesAsync()无法返回error 500

如果用户打开“编辑详细信息”对话框,未更改任何内容,然后单击发送请求的“编辑”按钮,则会发生这种情况。

我可以在客户端验证,这很好,但我很惊讶这导致了错误。

任何人都可以解释为什么会失败以及我应该在哪里纠正这个问题?

1 个答案:

答案 0 :(得分:2)

根据您解释的逻辑

  

如果用户打开“编辑详细信息”对话框,未更改任何内容,然后单击发送请求的“编辑”按钮,则会发生这种情况。

和这段代码

//...code removed for brevity

// Save the updated Area entity, added to the DbContext, to the SQL database.
if (await _areaRepository.SaveChangesAsync())
{
    var areaFromRepo = _areaRepository.GetArea(id);
    if (areaFromRepo == null)
        return NotFound();

    var area = Mapper.Map<AreaDto>(areaFromRepo);
    return Ok(area);
}

// The save has failed.
_logger.LogWarning($"Updating Area {id} failed on save.");
throw new Exception($"Updating Area {id} failed on save.");

如果未对文件进行任何更改并尝试更新,则不会对DbContext进行任何更改,这意味着_areaRepository.SaveChangesAsync()将为false,从而继续< / p>

// The save has failed.
_logger.LogWarning($"Updating Area {id} failed on save.");
throw new Exception($"Updating Area {id} failed on save.");
服务器上的

BAM 500错误。

我建议调试/单步执行可疑代码以确认其行为如上所述,然后重新思考并重构更新逻辑。