SignalR Core-从WebAPI检查连接状态

gar*_*thb 1 c# connection signalr.client asp.net-core asp.net-core-signalr

我正在使用Microsoft.AspNetCore.SignalR.Client从WebAPI项目打开的连接来连接和调用SignalR Hub项目中的方法。这些是托管在单独服务器上的单独项目。

如何检查连接是否已启动,所以我不会尝试两次启动?

我使用以下代码从WebAPI连接:

public class ChatApi
{
    private readonly HubConnection _connection;

    public ChatApi()
    {
        var connection = new HubConnectionBuilder();
        _connection = connection.WithUrl("https://localhost:44302/chathub").Build();
    }

    public async Task SendMessage(Msg Model)
    {
        await _connection.StartAsync();
        await _connection.SendAsync("Send", model);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我的WebAPI将大量调用SignalR,因此我想在WebAPI和SignalR之间创建单个连接,而不是每次都关闭/打开该连接。此刻,我将ChatApi类创建为单例,并在构造函数中初始化集线器连接。

在致电之前,我如何检查连接是否已启动await _connection.StartAsync();

使用:Microsoft.AspNetCore.SignalR.Clientv1.0.0-preview1-final

aar*_*ron 6

没有ConnectionState财产。

您需要通过订阅上的Closed事件来自己跟踪状态HubConnection

public class ChatApi
{
    private readonly HubConnection _connection;

    private ConnectionState _connectionState = ConnectionState.Disconnected;

    public ChatApi()
    {
        var connection = new HubConnectionBuilder();
        _connection = connection.WithUrl("https://localhost:44302/chathub").Build();

        // Subscribe to event
        _connection.Closed += (ex) =>
        {
            if (ex == null)
            {
                Trace.WriteLine("Connection terminated");
                _connectionState = ConnectionState.Disconnected;
            }
            else
            {
                Trace.WriteLine($"Connection terminated with error: {ex.GetType()}: {ex.Message}");
                _connectionState = ConnectionState.Faulted;
            }
        };
    }

    public async Task StartIfNeededAsync()
    {
        if (_connectionState == ConnectionState.Connected)
        {
            return;
        }

        try
        {
            await _connection.StartAsync();
            _connectionState = ConnectionState.Connected;
        }
        catch (Exception ex)
        {
            Trace.WriteLine($"Connection.Start Failed: {ex.GetType()}: {ex.Message}");
            _connectionState = ConnectionState.Faulted;
            throw;
        }
    }

    private enum ConnectionState
    {
        Connected,
        Disconnected,
        Faulted
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

public async Task SendMessage(Msg model)
{
    await StartIfNeededAsync();
    await _connection.SendAsync("Send", model);
}
Run Code Online (Sandbox Code Playgroud)

参考:SignalR / benchmarkapps / Crankier / Client.cs