.NET 6配置CORS后仍报错,Angular跨域请求问题求助
.NET 6 + Angular 跨域问题排查求助
问题描述
我在.NET 6与Angular搭建的Web项目中,已配置CORS但仍出现跨域错误。前端端口为4420,后端端口为7126,请求协助排查问题。
后端Program.cs CORS配置代码
var policyName = "_myAllowSpecificOrigins"; var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy(name: policyName, builder => { builder .WithOrigins("https://localhost:4420","http://localhost:4420") // 指定允许的源 .AllowAnyMethod() // 允许任意HTTP方法 .AllowAnyHeader() .AllowCredentials(); // 允许携带凭证 }); }); var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddIdentityServer() .AddApiAuthorization<ApplicationUser,ApplicationDbContext>(); builder.Services.AddAuthentication() .AddIdentityServerJwt(); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); builder.Services.AddTransient<IUnitOfWork, UnitOfWork>(); var app = builder.Build(); // 配置HTTP请求管道 if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(policyName); app.UseAuthentication(); app.UseAuthorization(); app.UseIdentityServer(); app.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); app.MapRazorPages(); app.MapFallbackToFile("index.html"); app.Run();
Angular前端请求代码
this.http.get("https://localhost:7126/images/logo.png", { withCredentials: true , responseType: 'blob' }).subscribe((response) => { const reader = new FileReader(); reader.onload = () => { this.imageUrl = reader.result as string; }; console.log("test"); reader.readAsDataURL(response); });
错误信息
- 控制台错误:跨域策略阻止请求,提示目标资源不存在
Access-Control-Allow-Origin响应头 - 网络请求详情:预请求(OPTIONS)的响应未包含正确的CORS相关头信息
排查与解决建议
1. 静态文件请求未触发CORS中间件
你请求的是静态文件(/images/logo.png),默认情况下UseStaticFiles中间件会直接处理这类请求,不会经过UseCors配置的策略。
解决方法:给静态文件单独配置CORS响应头,修改UseStaticFiles的配置:
app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "https://localhost:4420"); ctx.Context.Response.Headers.Append("Access-Control-Allow-Credentials", "true"); } });
2. 处理OPTIONS预请求
带凭证的跨域请求会先发送OPTIONS预请求,需确保后端能正确响应并返回CORS头。可添加全局中间件处理OPTIONS请求,将其放在UseStaticFiles之前:
app.Use(async (context, next) => { if (context.Request.Method == "OPTIONS") { context.Response.Headers.Append("Access-Control-Allow-Origin", "https://localhost:4420"); context.Response.Headers.Append("Access-Control-Allow-Credentials", "true"); context.Response.Headers.Append("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); context.Response.Headers.Append("Access-Control-Allow-Headers", "Content-Type, Authorization"); context.Response.StatusCode = 200; return; } await next(); });
3. 验证Origin匹配
确认前端实际运行的协议(http/https)和端口与WithOrigins中配置的完全一致,无拼写错误。
内容的提问来源于stack exchange,提问作者Кристијан Давитковски
相关产品推荐
相关产品推荐

