Skip to main content
 首页 » 编程设计

c#之Web api post方法上的空参数

2024年01月26日31grandyang

我有一个非常简单的 web api Controller :

public class CarrinhoController : ApiController 
    { 
        [HttpPost] 
        public string Adiciona([FromBody] string conteudo) 
        { 
            return "<status>sucesso</status"; 
        } 
    } 

现在我正在运行服务器并尝试通过 curl 测试此方法,如下所示:

curl --data "teste" http://localhost:52603/api/carrinho 

请求到达我的 Controller 。但是,参数 conteudo 始终为空。

我做错了什么?

谢谢。

请您参考如下方法:

这些帖子详细解释了类似的问题http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

在 asp.net 网站上 http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body.

在 Fiddler 上添加“Content-Type: application/json”即可。