通过Ajax向C# MVC接口发送JSON但接收为空的问题排查
解决Ajax发送JSON到C#接口接收为空的问题
关键修复要点
- 强制添加
[FromBody]特性:ASP.NET Core默认不会从请求体自动解析JSON绑定到参数,必须在Action的参数前标注[FromBody],才能触发请求体的JSON解析逻辑。 - 修正布尔类型参数传递:C#模型中
TalEstatus是bool类型,前端传递的1虽然部分序列化库能兼容转换,但直接传true能避免类型解析失败的潜在问题。 - 验证序列化配置:如果使用System.Text.Json,需确认项目配置是否支持必要的类型转换;若依赖Newtonsoft.Json,要确保已在服务中注册相关支持。
修正后代码示例
JavaScript代码
var settings = { "url": "Configuracion/CreateTallas", "method": "POST", "timeout": 0, "headers": { "Content-Type": "application/json" }, "data": JSON.stringify({ "TalTalla": "XXS", "TalFechaAlta": "2023-01-13T20:37:53.492Z", "TalDescripcion": "Extra Chica", "TalEstatus": true }), }; $.ajax(settings).done(function (response) { console.log(response); });
C#代码
public partial class UntCatTalla { public int TalId { get; set; } public string TalTalla { get; set; } = null!; public DateTime TalFechaAlta { get; set; } public string? TalDescripcion { get; set; } public bool TalEstatus { get; set; } } [HttpPost] public IActionResult CreateTallas([FromBody] UntCatTalla newTalla) { return Ok(_configs.CreateTallas(newTalla)); }
额外排查项
- 确认请求URL与控制器路由匹配,比如控制器类是否命名为
ConfiguracionController。 - 打开浏览器开发者工具的Network标签,检查请求的
Content-Type是否确实为application/json,且请求体的JSON格式无语法错误。 - 若使用System.Text.Json,可在Program.cs中配置更宽松的序列化规则,兼容数字转布尔等场景:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; });
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

