SignalR连接Hub出现CORS跨域错误如何解决?本地调试正常IIS部署报错
问题核心原因
- 现有CORS配置违反CORS规范:
AllowAnyOrigin()与AllowCredentials()不可同时使用,当允许携带凭证(Cookie/认证头)时,Access-Control-Allow-Origin不允许设置为通配符*,因此ASP.NET Core不会返回正确的CORS响应头,直接导致预检请求失败。 - 全局授权过滤器拦截了OPTIONS预检请求:SignalR的CORS预检请求不会携带Windows身份认证凭证,会被你配置的全局身份验证要求直接拦截,请求无法到达CORS中间件返回响应头。
- 部署到IIS后可能存在谓词拦截:IIS默认可能禁用OPTIONS谓词,或IIS自带的CORS模块与代码中CORS配置冲突。
修复步骤
1. 修正CORS配置,替换通配符源为实际允许的域名
修改ConfigureServices方法中的CORS注册代码,定义命名CORS策略,明确指定允许的前端源地址:
public void ConfigureServices(IServiceCollection services) { // 注册命名CORS策略 services.AddCors(options => { options.AddPolicy("AllowSignalRClients", policy => { // 填入你实际需要允许的前端域名,包括IIS部署的前端地址 policy.WithOrigins("http://iisServer", "http://localhost:4200", "http://schi-iis1zsus") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddSignalR(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAuthentication(IISDefaults.AuthenticationScheme); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddDbContext<FAContext>(options => options.UseSqlServer(Configuration.GetConnectionString("FADB"))); }
2. 调整中间件顺序,添加OPTIONS请求放行逻辑
在Configure方法中使用上述定义的CORS策略,并添加中间件优先放行OPTIONS预检请求,避免被授权拦截:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // 必须放在所有中间件最前面 app.UseCors("AllowSignalRClients"); // 放行OPTIONS预检请求,避免被后续授权拦截 app.Use(async (context, next) => { if (context.Request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = StatusCodes.Status200OK; await context.Response.CompleteAsync(); return; } await next(); }); app.UseSignalR(routes => { routes.MapHub<Hubs.HubFA>("/signalr"); }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); }
3. 修正IIS配置
- 关闭IIS站点的CORS功能,避免IIS自带的CORS模块覆盖代码返回的响应头
- 检查IIS站点的「请求筛选」设置,确保OPTIONS谓词被允许
- 检查站点的web.config,确认没有禁用OPTIONS谓词的配置
内容的提问来源于stack exchange,提问作者Ruben Martinez
相关产品推荐
相关产品推荐

