Posted parameter comes up blank in .NET Core 3.0 API

Viewed 1596

I created ASP.net core 3.0 web API application and added HttpPost endpoint to it.

When I post using postman to this post endpoint, the endpoint doesn't get the JSON I pass to it and instead gets null.

Is there something that has changed in .NET Core 3.0 that has changed/broken HTTP post endpoints?

The JSON I posted:

{
  "status": "0",
  "operation":"",
  "filter":"",
  "currentOrderList": [
  ]
}

Controller code:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET: api/<controller>
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

The url I am posting to is https://localhost:44336/api/values. I can see that the endpoint is being hit by the fact that the method is being hit during debugging in visual studio. The only issue is that the parameter is coming in as null

2 Answers

Create a model to match the given data

public class MyClass {
    [JsonProperty("status")]
    public int Status { get; set; }
    [JsonProperty("operation")]
    public string Operation { get; set; }
    [JsonProperty("filter")]
    public string Filter { get; set; }
    [JsonProperty("currentOrderList")]
    public string[] CurrentOrderList { get; set; }
}

Then update the controller action to expect the desired type

//POST api/values
[HttpPost]
public IActionResult Post([FromBody]MyClass value) {
    if(ModelState.IsValid) {
        //...
        return Ok();
    }
    return BadRequest();
}

In addition to adding the [JsonProperty] annotations as Nkosi said, I also had to add the nuget package

Microsoft.AspNetCore.Mvc.NewtonsoftJson

and append .AddNewtonsoftJson() into Startup.cs. I found that in another stackoverflow question, but neither change by itself was enough to get my models to hydrate. It took both to get it working.

services.AddMvc().AddRazorRuntimeCompilation().AddNewtonsoftJson();
Related