.NET Core Web API跨域GET请求异常:jQuery回调误进错误函数求助
解决跨域调用.NET Core Web API时AJAX进入错误回调的问题
我来帮你分析并解决这个问题——你遇到的情况其实是跨域请求处理不当加上前端回调逻辑不匹配API返回格式导致的,咱们一步步来修复:
问题根源拆解
- 跨域限制:你的静态页面是
file://协议,API是http://localhost:5000,属于不同源,浏览器的同源策略会拦截正常的AJAX请求。你虽然加了callback=?(JSONP的写法),但你的API并没有返回JSONP格式的响应,只是普通的JSON字符串,所以jQuery处理时会判定为失败,进入错误回调,但实际上HTTP请求本身是成功的,所以statusText显示"Success"。 - 响应格式不匹配:你的API返回的是纯字符串
"Test",但前端success回调里去判断data.success——这里的data就是字符串"Test",根本没有success属性,就算跨域问题解决了,逻辑也会出错。
下面给你两种靠谱的解决方案,优先推荐第一种:
方案一:配置CORS(推荐,支持所有HTTP方法)
CORS是现代跨域解决方案,比JSONP更灵活,步骤如下:
1. 在.NET Core API中配置CORS服务
打开API项目的Program.cs(.NET 6+),添加CORS服务和中间件:
var builder = WebApplication.CreateBuilder(args); // 添加CORS策略,开发环境允许所有来源(生产环境请替换为具体域名) builder.Services.AddCors(options => { options.AddPolicy("AllowAllOrigins", policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // 注册控制器服务 builder.Services.AddControllers(); var app = builder.Build(); // 必须在UseRouting之后、UseAuthorization之前添加CORS中间件 app.UseCors("AllowAllOrigins"); app.UseAuthorization(); app.MapControllers(); app.Run();
2. 修改前端AJAX代码
去掉callback=?,调整dataType和success回调逻辑(因为API返回的是纯字符串):
$(document).ready(function () { $.ajax({ type: 'GET', url: "http://localhost:5000/api/mycontroller/GetText", contentType: "application/json; charset=utf-8", dataType: 'json', success: function (data) { // 这里的data就是API返回的"Test"字符串 alert('Success -> ' + data); }, error: function (xhr, status, error) { alert('Error -> ' + status + ': ' + error); } }); });
方案二:使用JSONP(仅适合GET请求场景)
如果你的场景只需要GET请求,也可以用JSONP来处理跨域:
1. 修改API接口支持JSONP
默认的JsonResult不支持JSONP,需要手动处理callback参数:
using Newtonsoft.Json; // 如果用Newtonsoft.Json,需先安装NuGet包 // 或者用System.Text.Json:using System.Text.Json; [HttpGet("GetText")] public async Task<IActionResult> GetText(string callback = null) { try { string welCome = "Test"; // 序列化字符串为JSON var json = JsonConvert.SerializeObject(welCome, new JsonSerializerSettings { Formatting = Formatting.Indented }); // 用System.Text.Json的写法: // var json = System.Text.Json.JsonSerializer.Serialize(welCome, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }); // 如果有callback参数,返回JSONP格式(包裹在回调函数中) if (!string.IsNullOrEmpty(callback)) { return Content($"{callback}({json});", "application/javascript"); } // 否则返回普通JSON return Content(json, "application/json"); } catch(Exception ex) { // 不要直接throw,返回错误状态码和信息 return StatusCode(500, $"服务器错误:{ex.Message}"); } }
2. 修改前端AJAX代码
将dataType改为jsonp,jQuery会自动添加callback参数:
$(document).ready(function () { $.ajax({ type: 'GET', url: "http://localhost:5000/api/mycontroller/GetText", contentType: "application/json; charset=utf-8", dataType: 'jsonp', // 改为jsonp,自动处理跨域 success: function (data) { alert('Success -> ' + data); }, error: function (xhr, status, error) { alert('Error -> ' + status + ': ' + error); } }); });
额外注意事项
- 生产环境中,CORS策略不要用
AllowAnyOrigin,请指定具体允许的域名(比如policy.WithOrigins("http://yourdomain.com")),避免安全风险。 - API的异常处理不要直接
throw ex,应该返回对应的HTTP错误状态码和信息,这样前端能更清晰地定位问题。
内容的提问来源于stack exchange,提问作者user5032790
相关产品推荐
相关产品推荐

