.NET Core与JavaScript POST请求报错及无类解析方案咨询
问题原因与解决方案
核心问题分析
- 请求头与内容不匹配:前端设置
Content-Type: text/plain,但实际发送的是JSON格式字符串,后端ASP.NET Core默认用JSON解析器处理[FromBody]参数,导致解析逻辑冲突,引发400错误。 - 字符串解析冲突:当后端用
[FromBody] string data时,JSON解析器要求请求体必须是带双引号包裹的JSON字符串(如"{\"key\":\"value\"}"),但前端直接发送的是{"key":"value"},被解析器识别为JSON对象而非字符串,因此抛出解析错误。
无需创建实体类的解决方案
步骤1:修正前端请求头
将Content-Type改为application/json,匹配实际发送的JSON内容:
return fetch(apiURL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }) .then(response => response.json())
步骤2:后端接收任意JSON结构(二选一)
方式一:使用内置JsonElement(推荐,无需额外依赖)
利用System.Text.Json的JsonElement接收任意JSON结构,直接转成字符串传给第三方API:
using System.Text.Json; [HttpPost] public async Task<string> PostProductAsync([FromBody] JsonElement data) { // 直接获取原始JSON字符串 string jsonData = data.GetRawText(); HttpResponseMessage response = await _client.PostAsync(path, new StringContent(jsonData, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); return json; }
方式二:使用Newtonsoft.Json的JObject(适用于依赖Newtonsoft的项目)
- 先安装NuGet包:
Microsoft.AspNetCore.Mvc.NewtonsoftJson - 在Program.cs中配置启用:
builder.Services.AddControllers().AddNewtonsoftJson();
- 修改后端方法:
using Newtonsoft.Json.Linq; [HttpPost] public async Task<string> PostProductAsync([FromBody] JObject data) { string jsonData = data.ToString(); HttpResponseMessage response = await _client.PostAsync(path, new StringContent(jsonData, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); return json; }
补充说明
Swagger能正常请求是因为它会自动适配后端参数格式:发送Content-Type: application/json,并将输入内容处理为符合JSON规范的字符串(带外层双引号),因此后端可以正确解析。
内容的提问来源于stack exchange,提问作者Smuk
相关产品推荐
相关产品推荐

