Andoird 无法连接到 Blazor 服务器上运行的 SignalR

问题描述 投票:0回答:1

我正在尝试连接到使用 android 托管的 .net 6 Core Blazor WASM 核心。

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.");
}

这是我的毕业典礼,

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

这是我在核心托管 Blazor WASM 上的中心

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");
});

你能指出我做错了什么吗?

android asp.net-core-signalr
1个回答
0
投票

检查您的代码和设置后,有一些建议供您排除故障。

  1. 确保您的 Android 设备未使用蜂窝数据网络,因为您使用的是

    192.168.254.173
    私有 IP。同网段下可以正常工作

  2. 确保参数相同,SignalR 客户端的 URL 应为 http://192.168.254.173:5050/notification?userid=1010072

  3. 尝试在OnConnectedAsync中设置断点,看看能否进入这个方法。

    ① 如果是,就可以调试了。会发现问题的。
    ② 如果没有,请按照第4点打包

    Cors

  4. 我们可以启用所有Origin进行测试。中间件顺序非常重要。

    public class Program
    {
        public static void Main(string[] args)
        {
            ...
            // allow all Origin
            builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyMethod()
                    .SetIsOriginAllowed(_ => true)
                    .AllowAnyHeader()
                    .AllowCredentials();
            }));
            ...
            var app = builder.Build();
    
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/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();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
    
            // add this line
            app.UseCors("CorsPolicy");
    
            app.UseAuthorization();
    
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
    
            app.Run();
        }
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.