简体   繁体   中英

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.

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.

在此处输入图片说明

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;

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

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! ... } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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