【问题标题】:Web Api HTTPPost not accepting intWeb Api HTTPPost 不接受 int
【发布时间】:2017-08-08 03:25:13
【问题描述】:

我试图只传递 bodyint 但它不起作用 为什么我需要创建一个具有 int 类型属性的类? (然后就可以了)

有效

[HttpPost]
[Route("api/UpdateMainReversed")]
public IHttpActionResult UpdateMainVerified(DataAccess.Entities.RequestMain mainValues)
    {  ....}

不工作

[HttpPost]
[Route("api/UpdateMainReversed")]
public IHttpActionResult UpdateMainVerified(int mainId)
    {  ....}

使用 Postman 进行测试

http://localhost:13497/api/UpdateMainReversed

身体

{
   "mainId" : 1615
}

【问题讨论】:

  • 你想在 body 或 url 中传递 int?
  • body,因为它的 POST 并且不应该传递 URL 以获取正确的 REST
  • 检查我的答案。

标签: c# asp.net-web-api asp.net-web-api2 postman asp.net-web-api-routing


【解决方案1】:

设置FromBody 属性。

要强制 Web API 从请求正文中读取简单类型,请将 [FromBody] 属性添加到参数中。

详情Link

[HttpPost]
[Route("api/UpdateMainReversed")]
public IHttpActionResult UpdateMainVerified([FromBody] int mainId)
    {  ....}

【讨论】:

  • { "message": "请求无效。", "messageDetail": "参数字典包含方法的不可为空类型 'System.Int32' 的参数 'mainId' 的空条目'System.Web.Http.IHttpActionResult AddProduct(Int32)' i
  • 设置内容类型:application/x-www-form-urlencoded
  • 那么它将不再是 JSON Muhammad ...我在你的情况 user6321478 ,如果有人有解决办法
【解决方案2】:

1.您的 [HttpPost] 需要一个 int 但从 body 传递一个 json 对象。你应该像下面这样传递 json 字符串。参数名不用提

2.你应该使用[FromBody]如下

[HttpPost]
    public void UpdateMainVerified([FromBody] int mainid)
    {

    }

这个链接解释得很好

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

【讨论】:

  • 干得好。我阅读了几篇文章并准备放弃,因为我可以将字符串而不是 int 传递给字符串 mainid ...但值为 null。这个解决方案确实有效!谢谢
  • 另外,如果使用 axios,将数据发布为 axios.post('/UpdateMainVerified', mainId) 而不是 json 即 axios.post('/UpdateMainVerified', {mainId: mainId})
猜你喜欢
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 2021-04-19
相关资源
最近更新 更多