局域网内其他机器连接AspNetCore SignalR Server失败求助
局域网内无法连接AspNetCore SignalR Server问题
问题现象
本地使用localhost访问SignalR Hub可正常建立连接,但局域网内其他机器通过服务器IP/机器名访问时,出现连接超时错误:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (192.168.10.120:80)
服务器端代码(HubServer.Program.cs)
public static void Main(string[] args) { getRegistrySettings(); WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton<WeatherForecastService>(); builder.Services.AddResponseCompression(opts => { opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( new[] { "application/octet-stream" }); }); builder.Services.AddCors(options => { options.AddPolicy("CORSPolicy", builder => builder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetIsOriginAllowed((hosts) => true)); }); WebApplication app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //CORS need to be enabled for calling SignalR service app.UseCors("CORSPolicy"); //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub(); app.MapHub<MCHub>("/mchub"); //app.MapFallbackToPage("/_Host"); app.Run(); }
客户端WPF代码
public MainWindow() { InitializeComponent(); //const string url = "http://localhost:5289/mchub"; const string url = "http://192.168.10.120/mcsrhub/mchub"; var queryString = new Dictionary<string, string> { { "CreatedBy", "me" }, { "UserId", "1234" }, { "MachineName", Environment.MachineName } }; var newUrl = new Uri(QueryHelpers.AddQueryString(url, queryString)); connection = new HubConnectionBuilder() .WithUrl(newUrl) //"http://localhost:5289/mchub") //5181/chathub") .WithAutomaticReconnect() .Build(); connection.Reconnecting += (sender) => { this.Dispatcher.Invoke(() => { var newMessage = "Attempting to reconnect..."; messages.Items.Add(newMessage); }); return Task.CompletedTask; }; connection.Reconnected += (sender) => { this.Dispatcher.Invoke(() => { var newMessage = "Reconnected to the server"; messages.Items.Clear(); messages.Items.Add(newMessage); }); return Task.CompletedTask; }; connection.Closed += (sender) => { this.Dispatcher.Invoke(() => { var newMessage = "Connection Closed"; messages.Items.Add(newMessage); openConnection.IsEnabled = true; sendMessage.IsEnabled = false; }); return Task.CompletedTask; }; } private async void openConnection_Click(object sender, RoutedEventArgs e) { connection.On<string, string>("ReceiveMessage", (user, message) => { this.Dispatcher.Invoke(() => { var newMessage = $"{user}: {message}"; messages.Items.Add(newMessage); }); }); try { await connection.StartAsync(); messages.Items.Add("Connection Started"); openConnection.IsEnabled = false; sendMessage.IsEnabled = true; } catch (Exception ex) { messages.Items.Add(ex.Message); } } private async void sendMessage_Click(object sender, RoutedEventArgs e) { try { await connection.InvokeAsync("SendMessage", "WPF Client", messageInput.Text); } catch (Exception ex) { messages.Items.Add(ex.Message); } }
已尝试操作
- 关闭两台机器的AVG杀毒软件
- 确认服务器80端口开放
- 添加CORS配置(允许任意方法、头部、凭据,允许所有来源)
补充信息
服务器由IIS托管
排查与解决方案
1. 检查IIS站点绑定
- 确保IIS站点绑定包含局域网可访问的IP(
192.168.10.120),而非仅localhost或127.0.0.1 - 确认绑定端口为80,且无其他服务占用该端口
2. 服务器防火墙配置
- 检查Windows Defender防火墙,添加入站规则允许80端口的HTTP流量
- 确保规则覆盖局域网所在的专用网络配置文件
3. 验证站点路径有效性
- 在服务器浏览器中访问
http://192.168.10.120/mcsrhub/mchub,确认能返回SignalR协商响应(非404错误) - 检查IIS中
/mcsrhub虚拟目录是否正确映射到项目物理路径
4. 确认ASP.NET Core模块配置
- 确保IIS已安装对应.NET版本的ASP.NET Core托管模块
- 站点应用程序池的.NET CLR版本需设置为
无托管代码
5. 网络连通性测试
- 在客户端执行
ping 192.168.10.120,确认基础网络连通 - 用
Test-NetConnection 192.168.10.120 -Port 80测试端口是否真正可达
6. 强制SignalR传输方式(可选)
若上述步骤无效,可强制客户端使用WebSocket或长轮询,避免协议受阻:
connection = new HubConnectionBuilder() .WithUrl(newUrl, options => { options.Transports = HttpTransportType.WebSockets | HttpTransportType.LongPolling; }) .WithAutomaticReconnect() .Build();
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

