我的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
。
如果用户打开“编辑详细信息”对话框,不进行任何更改,然后单击发送请求的“编辑”按钮,则会发生这种情况。
我可以在客户端上进行验证,这很好,但是令我惊讶的是,这导致了错误。
谁能解释为什么这失败了,我应该在哪里纠正呢?
根据你解释的逻辑
如果用户打开“编辑详细信息”对话框,不进行任何更改,然后单击发送请求的“编辑”按钮,则会发生这种情况。
和这段代码
//...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
继续进行到
// The save has failed.
_logger.LogWarning($"Updating Area {id} failed on save.");
throw new Exception($"Updating Area {id} failed on save.");
和服务器上的BAM 500错误。
我建议调试/逐步执行可疑代码以确认其行为是否如上所述,然后重新考虑并重构更新逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句