【问题标题】:How to retrieve POST body data in ApiController?如何在 ApiController 中检索 POST 正文数据?
【发布时间】:2013-12-13 04:42:21
【问题描述】:

我正在使用 asp.net 4.5 和最新的 MVC 版本。在 html 页面中发布表单时,我需要从标题中检索 deviceIdbody。在public void Post([FromBody]string value) 行的值始终为空。

我在这里做错了什么?

  namespace WebApi.Controllers
    {
        public class NotificationController : ApiController
        {
            // GET api/notification
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/notification/5
            public string Get(int id)
            {
                return "value";
            }

            // POST api/notification
            public void Post([FromBody]string value)
            {
// value it is always null
            }

            // PUT api/notification/5
            public void Put(int id, [FromBody]string value)
            {
            }

            // DELETE api/notification/5
            public void Delete(int id)
            {
            }
        }
    }


<form action="/api/notification" method="post">
    DeviceId: <input name="deviceId" value="gateeMachine">
    Body: <input name="body" value="Warning Out of Paper">
    <button>Tes send</button>
</form>

【问题讨论】:

    标签: c# html asp.net-mvc


    【解决方案1】:

    您的帖子接受了一个参数“值”,而您正尝试向其发送两个参数“deviceId”和“body”。解决这个问题将是一个不错的起点。

    【讨论】:

      【解决方案2】:

      模型绑定器将参数与表单中名称属性的值相匹配。我发现创建模型并不那么令人头疼(以下是未经测试的代码):

      public class Devices
      {
           public string DeviceId { get; set; }
           public string Body { get; set; }
      }
      

      行动:

      public void Post(Devices device)
      {
      
      }
      

      形式:

      <form action="/api/notification" method="post">
          Device Id: <input name="DeviceId" value="gateeMachine">
          Body: <input name="Body" value="Warning Out of Paper">
          <button>Test send</button>
      </form>
      

      -- 编辑:事实证明不支持绑定多个表单值(请参阅this 答案),因此模型是要走的路。您可以将表单值序列化到查询字符串中。您还可以将值序列化为单个字符串(即 JSON 或 XML),然后在服务器端反序列化,但实际上,模型是这里最直接的路径。

      【讨论】:

      • 使用没有模型的第一种方法我得到 Can't bind multiple parameters ('deviceId' and 'body') to the request's content...任何想法?
      • 你知道为什么 ([FromBody]string deviceId, [FromBody]string body) 不起作用吗?
      猜你喜欢
      • 2021-07-21
      • 2021-02-08
      • 1970-01-01
      • 2014-11-15
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2011-06-28
      相关资源
      最近更新 更多