.NET 6(LTS)部署至Windows服务器后AJAX调用接口报500错误
部署到Windows服务器后AJAX调用Controller出现HTTP 500错误(本地调试正常)
本地Visual Studio调试时,通过AJAX从CSHTML页面向Controller发送C# DTO对象的功能正常,但部署到Windows宿主服务器后,点击按钮调用Action执行逻辑时出现URL未找到的HTTP 500错误,预期是返回JSON数据展示条码图片及相关详情。
前端JS代码
function sendTocreate() { $("#loading").show(); const BarcodeCreated = new FormData(); BarcodeCreated.append("airlineCode", $("#airlineCode option:selected").val()); BarcodeCreated.append("airlineName", $("#airlineName").val()); BarcodeCreated.append("mawb", $("#mawb").val()); BarcodeCreated.append("destination", $("#destination").val()); BarcodeCreated.append("origin", $("#origin").val()); BarcodeCreated.append("package", $("#package").val()); BarcodeCreated.append("weight", $("#weight").val()); BarcodeCreated.append("hawb", $("#hawb").val()); BarcodeCreated.append("company", $("#company").val()); BarcodeCreated.append("nosCopy", $("#nosCopy").val()); $.ajax({ type: 'POST', url: '/barcodeManager/barcodeCreat', data: BarcodeCreated, processData: false, contentType: false, success: function (data) { $("#loading").hide(); console.log(data.result); if (data.success) { $("#loading").hide(); $("#partialViewContainer").load("/barcodeManager/PartialViewAction{data:JSON.stringify(data.result) }); } else { Swal.fire({ title: 'Something Went Wrong With Server !!!', icon: 'warning' }).then((result) => { window.location.reload(); }) } }, error: function (error) { $("#loading").hide(); console.log(error); } }); }
后端C# .NET Core 6代码
[HttpPost] public JsonResult barcodeCreat(BarcodeCreated BarcodeCreated ){ string airline = BarcodeCreated.airlineName; // 读取11个DTO属性,执行条码创建逻辑并保存到SQL数据库,最终返回创建的条码详情JSON var result = // 此处为实际生成条码的逻辑代码 return Json(new{success=true,data=result}); }
问题排查及解决办法
URL路径硬编码问题:部署后应用可能存在虚拟目录,硬编码的路径无法匹配。改用
Url.Action生成正确的路由路径:url: '@Url.Action("barcodeCreat", "barcodeManager")',若JS代码在单独文件中,需先在CSHTML页面输出路径变量,再在JS中引用。
路由大小写敏感性:.NET Core路由默认可能区分大小写,确保Action名称
barcodeCreat与JS中URL的大小写完全一致;或在Program.cs中关闭大小写敏感:app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}", options: new RouteOptions { CaseInsensitive = true } ); });应用池权限不足:检查服务器上应用池的身份配置,确保其拥有数据库读写权限、条码生成目录的读写权限。
DTO绑定不匹配:确认FormData中的键名与
BarcodeCreated类的属性名完全一致(包括大小写、拼写),否则会导致参数绑定失败触发500错误。获取详细错误信息:在服务器端启用详细日志排查具体异常:
- 修改appsettings.json:
"DetailedErrors": true, "Logging": { "LogLevel": { "Microsoft.AspNetCore": "Debug" } } - 在IIS中开启站点的“详细错误”选项,查看完整的异常堆栈信息。
- 修改appsettings.json:
PartialView加载语法错误:成功回调中的PartialView加载路径存在硬编码和语法错误,修正为:
$("#partialViewContainer").load('@Url.Action("PartialViewAction", "barcodeManager")', { data: JSON.stringify(data.result) });
内容的提问来源于stack exchange,提问作者Anand Sahani
相关产品推荐
相关产品推荐

