jQuery Ajax POST请求WebAPI 2.1控制器失败:未找到匹配HTTP资源
问题原因
当前错误是因为WebAPI无法将你发送的JSON请求体与控制器方法的三个独立字符串参数绑定——默认情况下,WebAPI会从URI查询字符串中获取简单类型参数,而你通过请求体发送JSON对象,导致找不到匹配的Action。
解决方案
1. 修正控制器代码
方式一:使用ViewModel封装参数(推荐)
创建与前端JSON结构匹配的ViewModel类,让WebAPI自动完成请求体绑定:
// 定义ViewModel public class DiscrepancyReportViewModel { public string lid { get; set; } public string ProblemTypes { get; set; } public string ProblemTypeOther { get; set; } } // 修正控制器方法 [Route("api/reportdiscrepancy")] [HttpPost] public async Task<IHttpActionResult> ReportDiscrepancy([FromBody] DiscrepancyReportViewModel model) { string retval = string.Empty; if (model == null) { return BadRequest("无效的请求数据"); } string lid = AppCore.Validation.StripToGUID(model.lid); string problemTypes = AppCore.Validation.StripToDigitInCSVFromStr(model.ProblemTypes); string problemTypeOther = AppCore.Validation.StripAllCharsForMetaTag(StripHtml(model.ProblemTypeOther)); var session = HttpContext.Current.Session; if (lid.Length == 36 && (problemTypes.Length > 0 || problemTypeOther.Length > 0)) { if (IsGUID(lid)) { if (session != null && !string.IsNullOrEmpty(session.SessionID)) { var dr = new Discrepancy { lid = lid, SessionId = session.SessionID, IPAddress = Ops.Site.GetUserIP(HttpContext.Current), UserId = "anonymous" }; if (User?.Identity?.IsAuthenticated == true) { dr.UserId = User.Identity.GetUserId(); } dr.ProblemTypeIds = problemTypes; dr.ProblemTypeOther = problemTypeOther; dr.idx = await DiscrepancyReportData.InsertDiscrepancyAsync(dr); if (dr.idx > 0) { retval = "success"; } } } } return Ok(retval); }
方式二:单个[FromBody]动态参数(不推荐,仅当不想创建ViewModel时)
如果不想创建ViewModel,可通过动态参数接收请求体:
[Route("api/reportdiscrepancy")] [HttpPost] public async Task<IHttpActionResult> ReportDiscrepancy([FromBody] dynamic model) { string lid = AppCore.Validation.StripToGUID(model.lid.ToString()); string problemTypes = AppCore.Validation.StripToDigitInCSVFromStr(model.ProblemTypes.ToString()); string problemTypeOther = AppCore.Validation.StripAllCharsForMetaTag(StripHtml(model.ProblemTypeOther.ToString())); // 后续逻辑同方式一 }
2. 修正jQuery代码(jQuery 3.x+)
优化请求路径与代码逻辑,确保格式匹配:
$("#btnSendReport").on('click', function (e) { e.preventDefault(); // 阻止默认提交行为 var parElem = $(this).closest('.report-container'); // 用closest替代多层parent,更可靠 var listID = parElem.find("#hidLID").val(); var problemTypes = parElem.find('option:selected').map(function () { return this.value; }).get().join(','); var problemTypeOther = parElem.find("#txtProblemTypeOther").val(); var requestData = { lid: listID, ProblemTypes: problemTypes, ProblemTypeOther: problemTypeOther }; $.ajax({ type: "POST", url: "/api/reportdiscrepancy", // 使用根相对路径,避免层级错误 data: JSON.stringify(requestData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log("提交成功:", response); // 可添加前端反馈逻辑,如提示用户、隐藏弹窗等 }, error: function (xhr, status, error) { console.error("提交失败:", status, error); } }); });
额外检查点
- 确认WebAPI配置启用JSON格式化:在
WebApiConfig.cs中添加
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
- 检查控制器类是否正确继承
ApiController,无冲突路由属性 - 确保请求URL的域名、端口与WebAPI部署地址一致,若跨域需配置CORS
内容的提问来源于stack exchange,提问作者MC9000
相关产品推荐
相关产品推荐

