.NET 6对接Angular时HTTP请求遭CORS拦截问题排查
问题分析与解决:HTTP请求被CORS拦截,HTTPS请求正常
问题背景
基于.NET 6开发的后端项目同时监听HTTPS(https://localhost:7184)和HTTP(http://localhost:5146)端口,Angular前端(http://localhost:4200)调用HTTPS接口正常,但调用HTTP接口时触发CORS策略拦截。
核心原因
问题出在中间件顺序和HTTPS重定向的冲突:
- 当前配置中,
UseHttpsRedirection中间件在UseCors之后执行。当前端发送HTTP请求到http://localhost:5146时,后端会先尝试执行CORS校验,但紧接着UseHttpsRedirection会将请求重定向到HTTPS地址https://localhost:7184。 - 浏览器处理跨域预检请求(OPTIONS)时,不允许预检请求被重定向,因此直接触发CORS错误。而HTTPS请求不会触发重定向流程,CORS中间件能正常响应预检请求,所以可以正常调用。
解决方案
方案一:开发环境禁用HTTPS重定向(推荐)
在开发环境中关闭HTTPS重定向,避免HTTP请求被强制跳转,让CORS中间件正常处理请求:
修改Program.cs中的中间件配置:
var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseRouting(); app.UseCors("MyPolicy"); // 仅在生产环境启用HTTPS重定向 if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); } app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
方案二:调整中间件顺序(备选)
如果需要在开发环境保留HTTPS重定向,可将UseHttpsRedirection移至UseCors之前,但需注意:这种方式下HTTP请求仍会被重定向到HTTPS,前端最终还是会访问HTTPS接口,只是不会触发CORS错误,不符合使用HTTP接口的需求,因此方案一更合适。
验证步骤
- 重启.NET后端项目
- 确认Angular的
environment.ts中APIEndpoint为http://localhost:5146/ - 重启Angular前端,测试HTTP接口调用
相关配置参考
.NET后端launchSettings.json
{ "$schema": "https://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:38144", "sslPort": 44337 } }, "profiles": { "BackEnd_BlogDemo": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", "applicationUrl": "https://localhost:7184;http://localhost:5146", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
CORS策略配置
builder.Services.AddCors(options => options.AddPolicy(name: "MyPolicy", policy => { policy.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader(); }));
Angular环境配置(environment.ts)
export const environment = { production: true, APIEndpoint: "http://localhost:5146/" };
CORS错误截图

内容的提问来源于stack exchange,提问作者ShadyRaso
相关产品推荐
相关产品推荐

