Using [FromBody]
string content on an ApiController
in ASP.NET Core 3.0 returns a validation error:
{"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title":"One or more validation errors occurred.",
"status":400,
"traceId":"|9dd96d96-4e64bafba4ba0245.",
"errors":{"$":["The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."]}}
when the client post data with content-type : application/json
How do I get the raw json data as a string in my api controller in .NET Core 3.0? Without the client having to update its content type?
[FromBody] attributeThe ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter. Input formatters are explained later in this article. When [FromBody] is applied to a complex type parameter, any binding source attributes applied to its properties are ignored.
The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.
Please note that we are able to send [FromBody] parameter in HTTP GET Request input.
The [FromBody] attribute can be applied on only one primitive parameter of an action method. It cannot be applied to multiple primitive parameters of the same action method.
Not sure this help but I think they made some change in .net core 3.0 Newtonsoft.JSON package so you can try this
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson
package.
In your startup.cs add
services.AddControllers().AddNewtonsoftJson();
If you are using asp.net core 3.0 then this has built-in JSON support. I have use the following and it works without setting the custom input handler.
[HttpPost]
public async Task<IActionResult> Index([FromBody] JsonElement body)
{
string json = System.Text.Json.JsonSerializer.Serialize(body);
return Ok();
}
Change [FromBody] string content
to [FromBody] object content
and then if you want/need to read as string use content.ToString()
If you change the parameter [FromBody] String value
to [FromBody] YourType value
it is automatically deserialised for you.
From:
// POST api/<SelectiveCallRulesController>
[HttpPost]
public async Task Post([FromBody] String rule)
{
...
To:
// POST api/<SelectiveCallRulesController>
[HttpPost]
public async Task Post([FromBody] SelectiveCallRule rule)
{
...
It had me going around until I realised the error message regarding deserialisation is correct!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With