使用jQuery Ajax请求.NET Core 2.0 Web API时Authorization头缺失问题
这个问题的核心是跨域请求的预检机制在起作用:当你发送带自定义头(比如Authorization)的跨域请求时,浏览器会先发送一个OPTIONS预检请求,询问服务器是否允许这个自定义头。如果服务器没有正确配置CORS规则允许Authorization头,浏览器就不会在后续的实际GET请求中携带这个头,自然Web API端就拿不到凭证,返回401。
下面是一步步的解决方案:
1. 配置Web API的CORS允许Authorization头
在ASP.NET Web API中,你需要明确告诉服务器允许跨域请求携带Authorization头,并且允许凭证传递:
局部控制器/方法配置
在你的API控制器或者目标方法上添加EnableCors属性,指定允许的源、头和凭证:
using System.Web.Http.Cors; [EnableCors(origins: "http://localhost:50891", headers: "authorization", methods: "*", AllowCredentials = true)] public class YourApiController : ApiController { // 你的API方法 [HttpGet] public IHttpActionResult Method() { // 业务逻辑代码 } }
全局配置
如果要让规则全局生效,在WebApiConfig.cs的Register方法中添加:
config.EnableCors(new EnableCorsAttribute("http://localhost:50891", "authorization", "*") { AllowCredentials = true });
划重点:
AllowCredentials = true是关键,它允许浏览器在跨域请求中发送凭证类的头(比如Authorization)。
2. 修改jQuery Ajax请求,启用跨域凭证传递
在你的Ajax配置中,必须添加xhrFields: { withCredentials: true },否则浏览器会忽略Authorization头的发送:
function getChiefComplaints() { var symptoms = $('#txtChiefComplaints').val(); symptoms = symptoms.replace(" ", "+"); $.ajax({ url: 'http://localhost:44322/method', type: 'GET', dataType: 'json', xhrFields: { withCredentials: true // 启用跨域凭证传递 }, headers: { "Authorization": "Basic topsecretcredentials" }, success: function (data) { WriteResponse(data); }, error: function () { alert('no data'); } }); }
3. 确保服务器正确响应OPTIONS预检请求
有些情况下,Web API可能不会自动处理OPTIONS请求,你需要手动在Global.asax中添加处理逻辑,返回正确的CORS响应头:
protected void Application_BeginRequest() { if (Request.HttpMethod == "OPTIONS") { Response.StatusCode = (int)HttpStatusCode.OK; Response.AppendHeader("Access-Control-Allow-Origin", "http://localhost:50891"); Response.AppendHeader("Access-Control-Allow-Headers", "authorization"); Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); Response.AppendHeader("Access-Control-Allow-Credentials", "true"); Response.End(); } }
验证步骤
修改完成后,你可以用浏览器开发者工具(Network标签)检查请求:
- 查看OPTIONS预检请求的响应头,确认包含
Access-Control-Allow-Headers: authorization和Access-Control-Allow-Credentials: true - 查看后续的GET请求,确认请求头中携带了
Authorization: Basic topsecretcredentials
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

