Asp.net Core Post parameter is always null

18,572

Solution 1

I just had to correct the double quotes in your POST request and it worked. Try this:

{"Ean":"1122u88991","Name":"Post test","Description":"Post test desc"}

See screenshot below.

Screenshot

Solution 2

I experience a similar problem but I had no check for the validity of the ModelState as the OP. When this happens, inspecting it in debug mode will likely point you to what's wrong with the model:

QuickWatch window

In this example I was using an invalid string 'A' as test value for a Guid property, so the model was always null.

Solution 3

Had the same problem. It turned out that I had no public parameterless constructor for class of incoming instance. In this case, Product had only protected constructors and parameter was always null no matter what. Hope it helps somebody.

Share:
18,572

Related videos on Youtube

martinv
Author by

martinv

Updated on June 04, 2022

Comments

  • martinv
    martinv over 1 year

    I'm sending POST from fiddler:

    POST http://localhost:55924/api/Product HTTP/1.1
    User-Agent: Fiddler
    Host: localhost:55924
    Content-Type: application/json; charset=utf-8
    Content-Length: 84
    
    {"Ean″:”1122u88991″,”Name″:”Post test″,"Description":"Post test desc"}
    

    But Post method always gets null.

    // POST api/Product
    [HttpPost]
    public IActionResult PostProduct([FromBody]Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        _repo.Add(product);
    
        return CreatedAtRoute("GetToode",product);
    }
    

    When I use [FormBody] product is always null, when not using it product is valued but with all fields being null. Product class is simple.

    public class Product
    {
        public int ProductID { get; set; }
        public string EAN { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? CategoryID { get; set; }
    }
    

    i tried adding NullValueHandling to ConfigureServices as proposed in post but no use.

    services.AddMvc()
        .AddJsonOptions(jsonOptions =>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });
    
    • Fabricio Koch
      Fabricio Koch about 7 years
      try it sending all properties. Include ProductID and CategoryID.
  • martinv
    martinv about 7 years
    Honestly I feel so so dumb right now, that I didn't noticed it myself.
  • jcespinoza
    jcespinoza over 4 years
    It is not clear what quotes this answer refers to because the question was since edited a few times. FYI, OP used a mix of ″ ” and " characters in the original request body.
  • Gimmly
    Gimmly over 3 years
    Thank you for the great answer! I was shooting in the dark before stumbling upon this