带有两个[FromBody]参数的动作 [英] Action with double [FromBody] parameters

查看:97
本文介绍了带有两个[FromBody]参数的动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem with passing 2 parameters to my [HttpPut] method. They are both marked with [FromBody] attribute and they are both nulls when I test that method with Postman. Controller reacts correctly by letting me into the method but i don't know how to write a correct JSON body to get correct response. I don't know if that's the right way of passing 2 parrameters marked by [FromBody] or if it's even possible/allowed. In general I want to update my BitPosition object by passing an old one and swapping it to a new one. Can you help ?

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

推荐答案

根据文档

每个动作最多可以用[FromBody]装饰一个参数"

"There can be at most one parameter per action decorated with [FromBody]"

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

So, I suggest you to merge the objects like this;

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

    public BitPosition NewBitPosition { get; set; }
}

方法看起来像;

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

示例Json请求应该是这样;

Sample Json request should be like this;

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

这篇关于带有两个[FromBody]参数的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆