首页 > 解决方案 > 无法连接到 Azure SignalR ServerlessHub 实例

问题描述

我无法连接到 ServerlessHub 实例。

我正在使用这个参考文档

客户:

var hubClient = new ClientSignalR();
await hubClient.Initialize("http://localhost:7093/api/LocationHub");

...

public async Task Initialize(string connectionUrl)
{
    _connectionUrl = connectionUrl;

    _hub = new HubConnectionBuilder()
        .WithUrl(_connectionUrl)
        .Build();

    await _hub.StartAsync(); // ERROR
}

服务器:

public class LocationHub : ServerlessHub
{
    private const string NewMessageTarget    = "newMessage";
    private const string NewConnectionTarget = "newConnection";

    [FunctionName(nameof(Negotiate))]
    public SignalRConnectionInfo Negotiate([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)
    {
        return Negotiate(req.Headers["x-ms-signalr-user-id"], GetClaims(req.Headers["Authorization"]));
    }

    [FunctionName(nameof(OnConnected))]
    public async Task OnConnected([SignalRTrigger] InvocationContext invocationContext, ILogger logger)
    {
        invocationContext.Headers.TryGetValue("Authorization", out var auth);
        await Clients.All.SendAsync(NewConnectionTarget, new NewConnection(invocationContext.ConnectionId, auth));
        logger.LogInformation($"{invocationContext.ConnectionId} has connected");
    }

    [FunctionAuthorize]
    [FunctionName(nameof(LocationUpdate))]
    public async Task LocationUpdate([SignalRTrigger] InvocationContext invocationContext, SubjectLocation update, ILogger logger)
    {
        await Clients.All.SendAsync(NewMessageTarget, new NewMessage(invocationContext, update));
        logger.LogInformation($"{invocationContext.ConnectionId} broadcast {update}");
    }

    class NewConnection
    {
        public string ConnectionId { get; }

        public string Authentication { get; }

        public NewConnection(string connectionId, string authentication)
        {
            ConnectionId   = connectionId;
            Authentication = authentication;
        }
    }

    class NewMessage
    {
        public string ConnectionId { get; }
        public string Sender { get; }
        public SubjectLocation Update { get; }

        public NewMessage(InvocationContext invocationContext, SubjectLocation update)
        {
            Sender       = string.IsNullOrEmpty(invocationContext.UserId) ? string.Empty : invocationContext.UserId;
            ConnectionId = invocationContext.ConnectionId;
            Update       = update;
        }
    }
}

}

附录:

在此处输入图像描述

在此处输入图像描述

标签: azure-signalr

解决方案


推荐阅读