I have an application perfectly functioning, built in Angular 13 and .NET Core 2.1. Now I am upgrading it to .NET 8.0. I have successfully upgraded all other features, but I'm stuck at receiving the parameters as JObject.
In the old version, I pass the parameters from frontend in JSON like this:
"{ "query": "dotNet" }"
And the structure of backend controller action is as follows.
[HttpPost]
public async Task<IActionResult> GetDataAsync([FromBody] JObject jSearchItems)
{
try
{
dynamic SearchItems = jSearchItems;
string query = SearchItems.query;
ServiceResponse response = await _Service.GetDataAsync(query);
return StatusCode((int)(response.IsValid ? HttpStatusCode.OK : HttpStatusCode.BadRequest), response);
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
Note that the type of function parameter is JObject.
In .NET core 2.1, this was working correctly, but when I upgraded it to .NET 8.0, the data is received as null in the controller method.
If I create a new model for parameters as follows:
class SearchItem
{
public string query { get; set; }
}
and change the type of parameters from JObject to SearchItem, then the data is received correctly.
But I do not want to create hundreds of classes because there are a lot of API methods in this application.
So how can I receive JSON parameters from post request as JObject in ASP.NET Core 8.0 controllers?
Try this:
first install nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson and then in program.cs add: