ASP.NET Core WebAPI启用CORS失败求助:跨域POST请求被拦截
解决ASP.NET Core WebAPI与React前端的CORS拦截问题
错误信息
Access to fetch at 'https://localhost:xxx/api/Registration/register' from origin 'http://localhost:xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
问题根源
你的ASP.NET Core配置存在两处关键错误:
UseCors配置逻辑错误:误用WithMethods指定跨域源,WithMethods实际用于允许HTTP请求方法,而非允许的源地址- 中间件顺序错误:
UseCors的位置不符合ASP.NET Core中间件执行顺序要求,导致CORS头无法正确注入响应
修正后的Program.cs配置
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // 添加服务到容器 builder.Services.AddControllers(); var _config = builder.Configuration; builder.Services.AddScoped<IUserRepository, StudentRepository>(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "User", Version = "v1" }); }); builder.Services.AddDbContext<DataContext>(opt => opt.UseSqlServer(_config.GetConnectionString("DefaultConnection"))); // 配置CORS策略,允许指定前端源 builder.Services.AddCors(options => { options.AddPolicy("AllowReactOrigin", policy => { // 替换为你的React前端实际运行地址(比如http://localhost:3000) policy.WithOrigins("http://localhost:xxx") .AllowAnyHeader() .AllowAnyMethod(); }); }); var app = builder.Build(); // 开发环境启用Swagger if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseRouting(); // 应用CORS策略,必须放在UseRouting之后、UseAuthorization之前 app.UseCors("AllowReactOrigin"); // app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run(); } }
关键修正说明
- CORS策略配置:使用
AddPolicy创建命名策略,通过WithOrigins明确指定允许的前端源地址;AllowAnyHeader和AllowAnyMethod确保支持POST请求所需的请求头和方法 - 中间件顺序:
UseCors必须在UseRouting之后、UseAuthorization之前执行,这是ASP.NET Core中间件的强制顺序要求,否则CORS规则无法生效
前端代码说明
你的React fetch请求配置无需修改,当前代码符合标准POST请求格式:
fetch('https://localhost:xxx/api/Registration/register',{ method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(items), }) .then((response) => response.json()) .then((items) => { console.log('Success:', items); })
内容的提问来源于stack exchange,提问作者poko hamilton
相关产品推荐
相关产品推荐

