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

AJAX POST请求调用.NET Web API失败,寻求问题排查方案

问题:jQuery AJAX调用Web API POST接口报400错误,Swagger调用正常

API控制器代码

[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> Create([FromBody] Transaction tran)
{
    tran.OrderDate = DateTime.Now;
     await _db.Transactions.AddAsync(tran);
    var result = await _db.SaveChangesAsync();
     
    return Ok(result);
}

前端AJAX调用代码

$("#button").on("click",function(){
    var tran =  {userId: "68a60d7d-e323-472f-a3d6-7df1babbd633",  amount: "100.67",  businessName: "TESLA",  transactionPurpose: "Electrical Vehicle" };
     $.ajax({
               type:"POST",
               dataType: "json",
               contentType: "application/json",   
               data: tran,
               url:"https://localhost:7143/api/Transaction/Create",
               success:function(data)
               {
                   alert('API resut is Success');
                   console.log(data);
               },
               error: function (xhr, textStatus, errorThrown) {
                           console.log('Error in Operation');
                       }
             });
});

浏览器控制台返回的400错误信息

{type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",…}
errors: {$: ["'u' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],…}
$: ["'u' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]
0: "'u' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
tran: ["The tran field is required."]
0: "The tran field is required."
status: 400
title: "One or more validation errors occurred."
traceId: "00-4156aea880b9869412d44dd83f4889a5-286644919e844504-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1"

Swagger正常调用的curl示例

curl -X 'POST' \   'https://localhost:7143/api/Transaction/Create' \
-H 'accept: */*' \   -H 'Content-Type: application/json' \   -d '{   "userId": "68a60d7d-e323-472f-a3d6-7df1babbd633",   "amount": "120",
"businessName": "Tesla",   "transactionPurpose": "ModelT" }'

响应头信息

access-control-allow-origin: *   content-type: application/json;
charset=utf-8   date: Wed,17 Aug 2022 09:53:31 GMT   server: Kestrel

原因分析

你设置了contentType: "application/json",但直接把JS对象tran传给data参数时,jQuery不会自动将其序列化为JSON字符串,而是默认按application/x-www-form-urlencoded格式编码成类似userId=xxx&amount=xxx的字符串。

当API接口接收到这个格式的内容时,会尝试按JSON解析,自然会报错——因为userId=xxx的开头是u,不是JSON的合法起始字符({或[),所以出现'u' is an invalid start of a value的错误,同时因为没解析到正确的JSON对象,tran参数为空,触发The tran field is required的验证错误。

而Swagger调用时,是把JSON字符串作为请求体发送的,符合接口[FromBody]的解析要求,所以正常。

解决方法

将JS对象tran通过JSON.stringify()方法序列化为JSON字符串后,再传给data参数:

$("#button").on("click",function(){
    var tran =  {userId: "68a60d7d-e323-472f-a3d6-7df1babbd633",  amount: "100.67",  businessName: "TESLA",  transactionPurpose: "Electrical Vehicle" };
     $.ajax({
               type:"POST",
               dataType: "json",
               contentType: "application/json",   
               data: JSON.stringify(tran), // 转换为JSON字符串
               url:"https://localhost:7143/api/Transaction/Create",
               success:function(data)
               {
                   alert('API result is Success');
                   console.log(data);
               },
               error: function (xhr, textStatus, errorThrown) {
                           console.log('Error in Operation');
                       }
             });
});

这样发送的请求体就是标准的JSON格式,和Swagger的请求一致,接口就能正确解析tran参数了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:45:53