【问题标题】:Bind route parameter & values from json body to the model将 json 正文中的路由参数和值绑定到模型
【发布时间】:2021-12-17 00:45:56
【问题描述】:

我在 .net core 3.1 Web API 项目中有一个 put API。

网址:https://localhost:44319/api/user/4

控制器方法:

[HttpPut("{id}")]
[ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)]
public async Task<ActionResult<UpdateUserCommandResponse>> PutUser(UpdateUserCommand updateUserCommand)
{}

UpdateUserCommand 模型:

 public class UpdateUserCommand : IRequest<UpdateUserCommandResponse>
 {
      [FromRoute(Name = "id")]
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }        
 }

是否可以从 URL 和 json 正文中的其余字段填充模型中的 ID?目前,Id 保持为 0 我也不想在模型中包含属性权,因为相同

--- 更新代码-----

        [HttpPut("{id}")]
        [ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)]
        public async Task<ActionResult<UpdateUserCommandResponse>> PutUser(UpdateUserCommand updateUserCommand)
        {
            var response = await _mediator.Send(updateUserCommand);
            return Ok(response);
        }

       public class UpdateUserCommand : IRequest<UpdateUserCommandResponse>
       {
            //[FromRoute]
            public int Id { get; set; }
            [FromForm]
            public string FirstName { get; set; }
            [FromForm]
       }

【问题讨论】:

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


    【解决方案1】:

    如果你选择 Content-Type,它会在没有任何属性的情况下正常工作

    application/x-www-form-urlencoded 
    //or  
    multipart/form-data 
    

    或者如果你还有一些问题,你可以试试这个

          public int Id { get; set; }
          [FromForm]
          public string FirstName { get; set; }
           [FromForm]
          public string LastName { get; set; }  
    

    如果您选择内容类型

    application/json
    

    你将不得不改变你的行为

    [HttpPut("{id}")]
    ... PutUser( int id, [FromBody] UpdateUserCommand updateUserCommand)
    {}
    

    并且恕我直言,删除 [ProducesResponseType(typeof(UpdateUserCommandResponse), StatusCodes.Status200OK)] 。我看不出你需要它做什么

    【讨论】:

    • 我已经按照您在此处的建议找到了最后一个选项。工作。但随后我必须手动将 id 分配给模型。如果我将 Content-Type 设置为 urlencoded 或 multipart,则模型始终为 null
    • @Jay 如果您使用 urlencoded 或 multipart,则必须删除 [FromBody]。
    • @Jay 贴出你用来获取 API 数据的代码
    • 这是方法签名。模型类中没有属性 & Content-Type 是 multipart/form-data。模型保持为空。 " public async Task> PutUser(UpdateUserCommand updateUserCommand) " 如果我​​设置 Content-Type=x-www-form-urlencoded,那么我会得到 Unsupported Media Type 错误
    • @Jay 请张贴您正在使用的代码。我想看看你是如何添加内容的
    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 2017-07-06
    • 2011-03-03
    • 2015-12-17
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多