简体   繁体   English

如何将表单数据发布到ASP.NET WebAPI 2?

[英]How can I POST form data to ASP.NET WebAPI 2?

I'm having trouble accessing parameters submitted via POST in my ASP.NET WebAPI 2 application. 我在ASP.NET WebAPI 2应用程序中无法访问通过POST提交的参数。 I hav a very trivial controller and an action, which simply captures the parameter and returns 200. 我有一个非常琐碎的控制器和一个动作,它仅捕获参数并返回200。

public IHttpActionResult Post([FromBody] string foo)
{
    return Ok();
}

And I'm making the request via cURL 我正在通过cURL发出请求

curl http://localhost:24196/api/checkpoints -XPOST -d foo=bar

The parameter ends up being null . 该参数最终为null The same happens when I try this with jQuery. 当我尝试使用jQuery时,也会发生相同的情况。

$.post("http://localhost:24196/api/checkpoints", { foo: "bar" })

I've found a post that seems to describe this issue , but I'm not sure if that's really the correct way to fix this (using the = encoding). 我发现有一篇帖子似乎描述了此问题 ,但是我不确定这是否是解决此问题的正确方法(使用=编码)。

What is the correct/standard way of talking to a WebAPI service, and how does the parameter binding actually work in these cases? 与WebAPI服务进行通信的正确/标准方式是什么?在这些情况下,参数绑定实际上如何工作?

As documented in the link, FromBody expects data in a certain way =foo - re: there is no "key". 如链接中所述, FromBody希望以某种方式FromBody数据=foo -re:没有“键”。 So: 所以:

Curl: 卷曲:

curl -X POST -d "=bar" http://localhost/controller

Jquery: jQuery的:

var _data = { "": "bar" };

Update: 更新:

Reference for this behavior: Sending simple types 此行为的参考: 发送简单类型

By default, Web API tries to get simple types from the request URI. 默认情况下,Web API尝试从请求URI中获取简单类型。 The FromBody attribute tells Web API to read the value from the request body. FromBody属性告诉Web API从请求主体读取值。

...If you need to get multiple values from the request body, define a complex type. ...如果您需要从请求正文中获取多个值,请定义一个复杂类型。

Second, the client needs to send the value with the following format: 其次,客户端需要使用以下格式发送值:

=value =价值

Hth... 心连心...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM