With an endpoint like this:
[HttpPost("[action]")]
public async Task<ActionResult> Import([FromBody]string request)
{
var list = JsonConvert.DeserializeObject<List<RequestQuote>>(request);
return NoContent();
}
request always seems to be null. It worked for a little while earlier today but not sure what changed.
Here is the client side where I do the call.
var json = JsonConvert.SerializeObject(payload);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.PostAsJsonAsync($"{endpoint}/api/v1.0/BatchImport/Import", data);
Payload is a List
Even when using
Import([FromBody] List<RequestQuote> request)
I get the same issue.
CodePudding user response:
If your controller has the [ApiController]
attribute, you can put the data type you want to parse as the parameter of the method. I believe what is happening is that your program is trying to parse the JSON to a string type, which isn't what you want. You can try the code below, which should achieve what you're looking for.
[HttpPost("[action]")]
public async Task<ActionResult> Import([FromBody]List<RequestQuote> list)
{
// The parsed object should now be available here as "list"
return NoContent();
}
Alternatively, this post suggests pulling the body of the request directly. Either solution should be valid.
CodePudding user response:
There is a bug in the code, the data is serialized twice, the second time when you use PostAsJsonAsync. Try this
var json = JsonConvert.SerializeObject(payload);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync($"{endpoint}/api/v1.0/BatchImport/Import", data);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ViewModel>(stringData);
}
and action should be
public async Task<ActionResult> Import([FromBody] List<RequestQuote> request)