gabsferreira
gabsferreira

Reputation: 3147

Null parameter on web api post method

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

Answers (4)

Alexander Fedin
Alexander Fedin

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,

  • Incoming json:
  • -

{
    "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

hazjack
hazjack

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.

enter image description here

Upvotes: 5

Matthew
Matthew

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

DavidG
DavidG

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

Related Questions