localhost环境下Kestrel运行的WebAPI CORS策略不生效问题求助
解决步骤
1. 移除web.config中的CORS自定义头配置
不要同时通过web.config自定义头和ASP.NET Core CORS中间件配置跨域,二者会冲突导致头异常,直接删掉<httpProtocol>下的所有Access-Control-Allow-*相关配置即可。
2. 修正Startup.cs中的CORS策略配置
取消相关注释,补全正确的策略配置,注意必须指定策略名称调用:
public IConfiguration Configuration { get; } readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; public void ConfigureServices(IServiceCollection services) { // ...... services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins("https://localhost:44381") // 直接填写前端源地址,不要加尾部斜杠,比通配符*兼容性更好 .AllowAnyHeader() .AllowAnyMethod(); // 如果后续需要传递Cookie、认证头等凭证,再加.AllowCredentials()即可 }); }); // ...... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ...... app.UseRouting(); // 必须指定你定义的策略名称,且位置要在UseRouting之后,UseAuthorization之前 app.UseCors(MyAllowSpecificOrigins); app.UseAuthentication(); app.UseAuthorization(); // ...... }
3. 配置web.config处理OPTIONS预检请求
你的报错明确提到预检请求未返回正常HTTP状态,绝大多数是IIS的WebDAV模块拦截了OPTIONS请求导致的,在web.config的<system.webServer>节点下添加如下配置:
<modules runAllManagedModulesForAllRequests="true"> <remove name="WebDAVModule" /> </modules> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers>
4. 前端ajax配置无需额外调整
你当前注释了withCredentials,跨域场景下crossDomain: true也可以省略,jQuery会自动识别跨域场景调整请求逻辑。
内容的提问来源于stack exchange,提问作者user266909
相关产品推荐
相关产品推荐

