ASP.NET Core 8.0 API部署后CORS预请求OPTIONS返回405且无响应头
解决ASP.NET Core 8 API CORS预请求405问题
1. 修正Program.cs中间件顺序与CORS绑定
你的配置存在两处关键问题:一是UseHttpsRedirection仅在开发环境启用,无法适配Elastic Beanstalk的HTTPS生产环境;二是未将CORS策略明确绑定到控制器路由。修改后的代码如下:
builder.Services.AddAuthorization(); builder.Services.AddCors(options => { options.AddPolicy("AllowSpecificOrigins", builder => { string[] allowedOrigins = new string[] { "https://my-website.netlify.app", "http://localhost:3000", "https://localhost:3000", "http://localhost:4000", "https://localhost:4000" }; builder.WithOrigins(allowedOrigins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); var app = builder.Build(); // 生产环境强制HTTPS重定向,适配Elastic Beanstalk配置 app.UseHttpsRedirection(); app.UseRouting(); // CORS中间件必须在认证、授权之前执行 app.UseCors("AllowSpecificOrigins"); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthentication(); app.UseAuthorization(); // 将CORS策略绑定到所有控制器路由 app.MapControllers().RequireCors("AllowSpecificOrigins"); app.Run();
2. 解决Elastic Beanstalk的IIS拦截OPTIONS请求问题
AWS Elastic Beanstalk的IIS默认会拦截OPTIONS请求,导致405错误。需在项目根目录添加web.config文件,配置允许OPTIONS方法:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <remove name="OPTIONSVerbHandler" /> <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="None" /> </handlers> <httpProtocol> <customHeaders> <!-- CORS头由ASP.NET Core后端处理,此处无需重复配置 --> </customHeaders> </httpProtocol> </system.webServer> </configuration>
3. 移除前端Netlify的CORS配置
headers.toml中配置的CORS头属于后端职责,前端配置会导致跨域响应头冲突,直接删除该文件或清空CORS相关配置即可。
验证步骤
- 重新部署API到Elastic Beanstalk
- 用浏览器开发者工具或Postman发起OPTIONS请求到API端点,检查响应头是否包含
Access-Control-Allow-Origin、Access-Control-Allow-Methods等CORS字段 - 测试前端正式请求是否正常执行
内容的提问来源于stack exchange,提问作者Roomba
相关产品推荐
相关产品推荐

