gpt4 book ai didi

c# - 如何在 ApiController 中检索 POST 正文数据?

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:25 24 4
gpt4 key购买 nike

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

我哪里做错了?

  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>

最佳答案

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

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>

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

关于c# - 如何在 ApiController 中检索 POST 正文数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com