如何在ASP.NET Core 8.0控制器中接收Post请求的JSON参数为JObject?
解决方案
方法1:切换回Newtonsoft.Json(Json.NET)
.NET 8默认使用System.Text.Json作为JSON序列化器,而JObject是Newtonsoft.Json的专属类型,因此需要重新配置项目使用Newtonsoft.Json来恢复旧行为:
- 安装NuGet包:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
或使用.NET CLI:
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
- 在
Program.cs中配置控制器使用NewtonsoftJson序列化:
var builder = WebApplication.CreateBuilder(args); // 添加控制器并启用NewtonsoftJson支持 builder.Services.AddControllers() .AddNewtonsoftJson(); var app = builder.Build(); // 其他中间件配置... app.MapControllers(); app.Run();
配置完成后,原有的JObject参数控制器方法可正常接收数据,无需修改任何控制器代码。
方法2:使用System.Text.Json原生的JsonElement
若不想依赖NewtonsoftJson,可改用System.Text.Json提供的JsonElement替代JObject,调整控制器方法如下:
[HttpPost] public async Task<IActionResult> GetDataAsync([FromBody] JsonElement jSearchItems) { try { string query = jSearchItems.GetProperty("query").GetString(); 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); } }
JsonElement是System.Text.Json的原生类型,支持动态读取JSON属性,无需额外安装依赖。
问题原因
.NET Core 3.0及后续版本(包括.NET 8)将默认JSON序列化器从Newtonsoft.Json替换为System.Text.Json。由于JObject属于Newtonsoft.Json的API,默认的System.Text.Json无法识别并完成请求体到JObject参数的绑定,因此会返回null。而强类型模型可被System.Text.Json正常解析,所以能正确接收数据。
内容的提问来源于stack exchange,提问作者Ali Shan
相关产品推荐
相关产品推荐

