SignalR在IIS中无法连接但本地正常的问题求助
本地环境下,API与两个客户端通过SignalR连接可正常接收通知,但部署到IIS服务器后,SignalR Hub无法建立连接,不过Controller中的Post和Get方法能正常运行。
客户端代码
@section Scripts{ <script type="text/javascript"> $(document).ready(() => { var connection = new signalR.HubConnectionBuilder() .withUrl("http://myDomain/denemehub") .withAutomaticReconnect() .build(); $("#constatus").text(connection.state); connection.start().then(() => { $("#constatus").text(connection.state); connection.invoke("DenemeAddedMessageAsync"); }).catch((err) => { console.log(err) }); connection.on("receiveProductAddedMessage", (value) => { $("#denemevalue").text(value); }); }); </script> }
API Program.cs 初始配置
builder.Services.AddCors(opt => { opt.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); app.UseCors("CorsPolicy"); app.MapHub<DenemeHub>("/denemehub");
修改后的CORS配置
builder.Services.AddCors(opt => { opt.AddPolicy("CorsPolicy", builder => { builder.WithOrigins("http://localhost:5171") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); });
Web.config 内容
<configuration> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> </modules> </system.webServer> </configuration>
控制台报错信息
Failed to load resource: net::ERR_SSL_PROTOCOL_ERRORWarning: Error from HTTP request. TypeError: Failed to fetch.Error: Failed to complete negotiation with the server: TypeError: Failed to fetchError: Failed to start the connection: Error: Failed to complete negotiation with the server: TypeError: Failed to fetch
已执行操作
- 已启用IIS的WebSocket协议
修复SSL/HTTP协议不匹配问题
报错ERR_SSL_PROTOCOL_ERROR说明客户端用HTTP请求,但服务器可能强制HTTPS。检查IIS站点是否绑定SSL证书,若服务器要求HTTPS,客户端需将withUrl改为https://myDomain/denemehub。同时确认IIS站点的“SSL设置”是否开启“要求SSL”,开启后必须使用HTTPS连接。调整CORS配置适配生产环境
修改后的CORS仅允许http://localhost:5171,部署后客户端若来自其他域名,需将实际客户端域名加入WithOrigins列表,例如:builder.WithOrigins("http://your-client-domain.com", "http://localhost:5171")注意:使用
AllowCredentials()时不能搭配AllowAnyOrigin(),必须明确指定允许的源,这点需保持配置一致性。验证WebSocket与IIS应用池配置
确认IIS应用池为集成模式(Web.config已设置validateIntegratedModeConfiguration="false",但仍需检查应用池设置)。同时再次确认WebSocket功能已正确安装:打开服务器管理器 -> 添加角色和功能 -> Web服务器 -> 应用开发 -> 勾选“WebSocket协议”。检查Hub路由与站点路径映射
确认IIS站点的物理路径正确指向API发布后的文件,尝试直接访问http(s)://myDomain/denemehub/negotiate,若返回404则说明路由未正确映射,需检查API发布包是否完整,或调整IIS站点的路由规则。客户端添加跨域凭据配置
因CORS开启了AllowCredentials(),客户端连接时需显式开启凭据传递:.withUrl("https://myDomain/denemehub", { withCredentials: true })
内容的提问来源于stack exchange,提问作者Berkay Baş

