双[FromBody]参数的动作

时间:2017-12-11 12:30:19

标签: c# asp.net-core

将2个参数传递给[HttpPut]方法时遇到问题。它们都标有[FromBody]属性,当我用Postman测试该方法时它们都是空的。控制器通过让我进入方法正确反应,但我不知道如何编写正确的JSON正文以获得正确的响应。我不知道这是否正确传递了由[FromBody]标记的2个参数,或者它是否可能/允许。一般来说,我想通过传递一个旧对象并将其交换为新对象来更新我的BitPosition对象。你能帮我吗 ?

[HttpPut]
public async Task<IActionResult> UpdateBitPosition([FromBody]BitPosition oldBitPosition, [FromBody]BitPosition newBitPosition)
{
    if (oldBitPosition == null || newBitPosition == null)
    {
        return BadRequest();
    }

    try
    {
        var bitPositionToUpdate = await _context.BitPositions.FirstOrDefaultAsync(bp => bp.IDPermission == oldBitPosition.IDPermission &&
                                                                                        bp.Position == oldBitPosition.Position);

        if (bitPositionToUpdate == null)
        {
            return NotFound();
        }

        bitPositionToUpdate.IDPermission = newBitPosition.IDPermission;
        bitPositionToUpdate.Position = newBitPosition.Position;

        _context.BitPositions.Update(bitPositionToUpdate);
        await _context.SaveChangesAsync();
        return new NoContentResult();
    }
    catch (Exception ex)
    {
        Helpers.ExceptionLogger.LogException(ex);
        return StatusCode(500);
    }
}

1 个答案:

答案 0 :(得分:3)

根据documentation

  

&#34;每个动作最多只能有一个参数用[FromBody]&#34;

装饰

所以,我建议你合并像这样的对象;

public class MergedBitPosition
{
    public BitPosition OldBitPosition { get; set; }

    public BitPosition NewBitPosition { get; set; }
}

方法看起来像;

public async Task<IActionResult> UpdateBitPosition([FromBody]MergedBitPosition mergedBitPosition)

示例Json请求应该是这样的;

{
   "OldBitPosition":{
      "IdPermission":8,
      "Position":1
   },
   "NewBitPosition":{
      "IdPermission":8,
      "Position":5
   }
}