ASP.NET Core Web Api中ApiKey中间件引发CORS报错求助
问题原因
当前中间件执行顺序错误:ApiKeyMiddleware 在 UseCors 之前运行。当API密钥验证失败返回401响应时,CORS中间件还未处理请求,导致响应中缺少Access-Control-Allow-Origin头,浏览器触发同源策略限制报错。Postman不受同源策略约束,因此能正常接收401响应,但浏览器不行。
解决方案
方案一:调整中间件顺序(推荐)
将UseCors移至ApiKeyMiddleware之前,确保CORS头在所有响应(包括401错误响应)中都能被正确添加。修改Program.cs的中间件注册部分:
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); // 先执行CORS中间件 app.UseCors(MyAllowSpecificOrigins); // 再执行API密钥验证中间件 app.UseMiddleware<ApiKeyMiddleware>(); app.UseAuthorization(); app.MapControllers(); app.Run();
同时建议完善CORS策略,允许自定义请求头(如XApiKey)和常用HTTP方法,避免预检请求失败:
builder.Services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, policy => { policy.WithOrigins("https://localhost:7029") .AllowAnyMethod() .AllowAnyHeader(); }); });
方案二:在API密钥中间件中手动添加CORS头(不推荐,灵活性差)
如果不想调整中间件顺序,可在返回401错误时手动添加CORS允许头:
public async Task InvokeAsync(HttpContext context) { if (!context.Request.Headers.TryGetValue(APIKEY, out var extractedApiKey)) { // 添加CORS允许头 context.Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:7029"); context.Response.StatusCode = 401; await context.Response.WriteAsync("Api Key was not provided "); return; } var appSettings = context.RequestServices.GetRequiredService<IConfiguration>(); var apiKey = appSettings.GetValue<string>(APIKEY); if (!apiKey.Equals(extractedApiKey)) { // 添加CORS允许头 context.Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:7029"); context.Response.StatusCode = 401; await context.Response.WriteAsync("Unauthorized client"); return; } await _next(context); }
内容的提问来源于stack exchange,提问作者user19575939
相关产品推荐
相关产品推荐

