简体   繁体   English

SignalR Core - 从 WebAPI 检查连接状态

[英]SignalR Core - Check connection state from WebAPI

I am using Microsoft.AspNetCore.SignalR.Client to open a connection from my WebAPI project to connect and call methods in my SignalR Hub project.我正在使用Microsoft.AspNetCore.SignalR.Client从我的 WebAPI 项目打开一个连接,以连接和调用我的 SignalR Hub 项目中的方法。 These are separate projects hosted on separate servers.这些是托管在不同服务器上的独立项目。

How do I check whether the connection has been started, so I don't try to start it twice?如何检查连接是否已启动,以免尝试启动两次?

I connect from WebAPI using the following code:我使用以下代码从 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);
    }
}

Since my WebAPI will be calling into SignalR quite a bit, I want to create the single connection between WebAPI and SignalR and not close/open the connection each time.由于我的 WebAPI 会大量调用 SignalR,因此我想在 WebAPI 和 SignalR 之间创建单个连接,而不是每次都关闭/打开连接。 At the moment I create the ChatApi class as a singleton and initialize the hub connection in the constructor.目前,我将ChatApi类创建为单例并在构造函数中初始化集线器连接。

How would I check if the connection is started before calling await _connection.StartAsync();在调用await _connection.StartAsync();之前,我将如何检查连接是否已启动await _connection.StartAsync(); ? ?

Using: Microsoft.AspNetCore.SignalR.Client v1.0.0-preview1-final使用: Microsoft.AspNetCore.SignalR.Client v1.0.0-preview1-final

There is no ConnectionState property.没有ConnectionState属性。

You need to track the state yourself, by subscribing to the Closed event on HubConnection .您需要通过订阅HubConnection上的Closed事件来自己跟踪状态。

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
    }
}

Usage:用法:

public async Task SendMessage(Msg model)
{
    await StartIfNeededAsync();
    await _connection.SendAsync("Send", model);
}

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

In .NET Core 2.1 at least, you can check the State property of your HubConnection:至少在 .NET Core 2.1 中,您可以检查 HubConnection 的State属性:

if (_connection.State == HubConnectionState.Disconnected) {
        await _connection.StartAsync();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM