You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android无法连接Blazor Server中运行的SignalR问题排查

Android连接Blazor WASM SignalR服务的错误点分析

问题描述

我正尝试使用Android连接.NET 6 Core托管的Blazor WASM应用的SignalR服务,请帮我指出操作有误的地方?


我的Android代码

String hubUrl = "http://192.168.254.173:5050/notification?parameter=1010072";
if (isReachable) {
    hubConnection = HubConnectionBuilder.create(hubUrl).build();
    if (hubConnection.getConnectionState() != HubConnectionState.CONNECTED) {
        hubConnection.start();
        hubConnection.on("MessageModelToClients", (messageModel) -> {
            Log.i("TAG", messageModel.getMessage());
        }, MessageModel.class);
        if (hubConnection.getConnectionState() == HubConnectionState.CONNECTED) {
            Log.i("TAG", "Connected");
        } else {
            Log.e("TAG", "Failed to establish connection to SignalR hub.");
        }
    }
} else {
    System.out.println("IP address is not reachable.");
}

Gradle配置

implementation ("com.microsoft.signalr:signalr:7.0.0")

Blazor WASM服务端NotificationHub代码

public class NotificationHub : Hub 
{
    ....
    
    public override async Task OnConnectedAsync()
    {
        Console.WriteLine("Connecting...");
        var userId= Context.GetHttpContext()!.Request.Query["userid"];
        var connectionId = Context.ConnectionId;
        AddUser(connectionId, userId);
        var messageModel = new MessageModel
        {
            IsPrivate = false,
            Message = $"Logged in User: {userId}",
            Recipient = string.Empty,
            Sender = SERVER_NAME
        };
        await SendConnectedUsers();
        await SendObjectToAll(messageModel);

        Console.WriteLine($"CONNECTED: {connectionId}");

        await base.OnConnectedAsync();
    }
    
    
    ...
}

Program.cs配置

builder.Services.AddSignalR();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<NotificationHub>("/notification");
});

错误点分析

  1. 异步连接未等待完成
    Android端hubConnection.start()是异步方法,调用后不会立即建立连接。直接同步检查连接状态会误判为失败,必须通过start().subscribe()监听连接结果,示例修正:

    hubConnection.start().subscribe(() -> {
        Log.i("TAG", "Connected");
    }, error -> {
        Log.e("TAG", "连接失败: " + error.getMessage());
    });
    
  2. 查询参数名不匹配
    服务端Hub获取的是userid参数,但Android端URL传的是parameter=1010072,参数名不一致导致服务端无法正确获取用户ID,需将URL改为:

    http://192.168.254.173:5050/notification?userid=1010072
    
  3. 消息监听注册时机错误
    应在启动连接之前注册hubConnection.on(),否则连接建立后服务端发送的初始消息(如OnConnectedAsync中的推送)会丢失。调整顺序为:先注册监听,再启动连接。

  4. SDK版本不匹配
    Android使用的SignalR SDK是7.0.0,而服务端是.NET 6,跨版本可能存在协议兼容问题,建议改用6.x版本的SignalR SDK:

    implementation ("com.microsoft.signalr:signalr:6.0.25")
    
  5. 缺少CORS配置检查
    若服务端未正确配置CORS允许Android客户端域名/IP访问,会导致连接失败。需在服务端Program.cs中添加CORS配置:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("SignalRCors", policy =>
        {
            policy.WithOrigins("http://你的Android客户端IP或域名")
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials();
        });
    });
    
    app.UseCors("SignalRCors");
    

内容的提问来源于stack exchange,提问作者Ibanez1408

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:07:06