【问题标题】:Web API - Get Values from Querystring and Form BodyWeb API - 从查询字符串和表单正文中获取值
【发布时间】:2014-04-11 14:30:38
【问题描述】:

我在 Web API 中有一个动作,其路由如下:

/users/{userId}/friends

我想通过以下操作向它发布一个值:

[ActionName("friends")]
        public IHttpActionResult Friends2(string userId, [FromBody]string friendId)

我发布的 JSON 格式如下:

{ "friendId": "123" }

但是,friendId 始终为空。我认为这是因为 Web API 在指定 [FromBody] 时只允许 1 个参数。

那么我怎样才能使用来自查询字符串的 userId 和作为正文中的 JSON 的friendId 发布到此操作?

【问题讨论】:

    标签: c# asp.net asp.net-web-api


    【解决方案1】:

    您可以使用控制器操作将作为参数的视图模型并绑定到正文中发送的 JSON 结构:

    public class MyViewModel
    {
        public string FriendId { get; set; }
    }
    

    然后:

    ActionName("friends")]
    public IHttpActionResult Friends2(string userId, MyViewModel model)
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多