You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript调用ASP.NET Core 7 Minimal API时JSON参数读取失败及断点未命中问题

问题分析与解决建议

核心原因

  1. 模型绑定不匹配:当请求头设置Content-Type: application/json时,ASP.NET Core的默认模型绑定器会将请求体解析为JSON对象,但你前端发送的是JSON格式的字符串(比如请求体内容是带引号的"{\"name\":\"xxx\"}")。此时绑定器尝试把JSON对象转换为string类型,类型不匹配直接触发BadHttpRequestException,请求根本没进入你的接口方法,所以断点无法命中。
  2. 请求预处理拦截:ASP.NET Core在请求到达你的业务代码前,会先完成模型绑定和参数校验,绑定失败时会直接返回400错误,不会执行接口内的逻辑。

解决建议

方案一:调整前端请求格式(推荐)

将JSON字符串包装为JSON对象的一个属性发送,后端通过实体类接收:

  • 前端修改请求体:
// 假设jsonString是你处理后的JSON字符串
const requestData = { instJson: jsonString };
axios.post('/api/institution', requestData, {
  headers: { 'Content-Type': 'application/json' }
});
  • 后端定义接收类并修改接口:
public class InstitutionRequest
{
    public string InstJson { get; set; }
}

app.MapPost("/api/institution", ([FromBody] InstitutionRequest request) => {
    var institution = JsonSerializer.Deserialize<Institution>(request.InstJson);
    // 后续数据操作
});

方案二:后端直接读取原始请求体

跳过模型绑定,直接读取请求体的原始字符串:

app.MapPost("/api/institution", async (HttpRequest req) => {
    using var streamReader = new StreamReader(req.Body);
    var instJson = await streamReader.ReadToEndAsync();
    var institution = JsonSerializer.Deserialize<Institution>(instJson);
    // 后续数据操作
});

方案三:修改前端请求头类型

将Content-Type改为text/plain,让后端直接识别为纯文本字符串:

  • 前端修改请求头:
axios.post('/api/institution', jsonString, {
  headers: { 'Content-Type': 'text/plain' }
});
  • 后端保持原接口逻辑即可:
app.MapPost("/api/institution", ([FromBody] string instJson) => {
    var institution = JsonSerializer.Deserialize<Institution>(instJson);
    // 后续数据操作
});

内容的提问来源于stack exchange,提问作者CB_at_Sw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:37:15