Reputation: 3147
I have a very simple web api controller:
public class CarrinhoController : ApiController
{
[HttpPost]
public string Adiciona([FromBody] string conteudo)
{
return "<status>sucesso</status";
}
}
Now I'm running the server and trying to test this method via curl
like this:
curl --data "teste" http://localhost:52603/api/carrinho
The request is arriving in my controller. However, the parameter conteudo
always comes empty.
What am I doing wrong?
Thanks.
Upvotes: 2
Views: 16819
Reputation: 11
You might have an incorrect (malformed) request. WebAPI uses JSON serializer that ignores malformed request errors and just passes null through.
As an example,
{
"MyProp":"<ASN xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>"
}
public class MyRequest
{
public string MyProp { get; set; }
}
Controller action:
[HttpPost]
[Route("inbound")]
[ResponseType(typeof(InboundDocument))]
public IHttpActionResult DoPost([FromBody]MyRequest myRequest)
{
if (myRequest == null) throw new ArgumentNullException(nameof(myRequest));//this line throws!
...
}
Upvotes: 0
Reputation: 1715
These posts explain similar problem in detail http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
On asp.net site 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.
Add "Content-Type: application/json" on Fiddler will work.
Upvotes: 5
Reputation: 25793
Depending on the Content-Type
you're sending determines how ASP.NET WebAPI binds parameters.
Try sending the following instead (form encoded)
conteudo=teste
Alternatively, if you don't want the binding to happen, you remove all parameters and read the posted data
var myContent = response.Content.ReadAsStringAsync().Result;
Upvotes: 2
Reputation: 119186
You need to name the parameter in the POST data to match the method parameter name. Change your curl
data parameter to be this format:
parameter=value
For example:
curl --data "conteudo=teste" http://localhost:52603/api/carrinho
Upvotes: 1