【问题标题】:SignalR Core - Check connection state from WebAPISignalR Core - 从 WebAPI 检查连接状态
【发布时间】:2018-04-12 00:36:52
【问题描述】:

我正在使用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);
    }
}

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

在调用await _connection.StartAsync();之前如何检查连接是否已启动?

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

【问题讨论】:

    标签: c# asp.net-core connection signalr.client asp.net-core-signalr


    【解决方案1】:

    Microsoft.AspNetCore.SignalR.Client v1.1.0+

    HubConnection 上有一个 State 属性。

    public class ChatApi
    {
        private readonly HubConnection _connection;
    
        public ChatApi()
        {
            _connection = new HubConnectionBuilder()
                .WithUrl("https://localhost:44302/chathub")
                .Build();
        }
    
        public async Task StartIfNeededAsync()
        {
            if (_connection.State == HubConnectionState.Disconnected)
            {
                await _connection.StartAsync();
            }
        }
    
        public async Task SendMessage(Msg model)
        {
            await StartIfNeededAsync();
            await _connection.SendAsync("Send", model);
        }
    }
    

    参考资料:

    Microsoft.AspNetCore.SignalR.Client

    (在撰写本文时,最新版本是 1.0.0-preview2-final。)

    没有ConnectionState 属性。

    您需要自己跟踪状态,方法是订阅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
        }
    }
    

    用法:

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

    参考资料:

    【讨论】:

    • @Seabizkit 是的,我已经更新了新版本的答案。
    • 谢谢! ,既然每个人都想要呵呵,你不想写单例类吗,它包含重试策略.. ;-) 感谢您的更新..
    • 这超出了这个问题的范围,链接文档中有一个不错的示例实现。
    【解决方案2】:

    至少在 .NET Core 2.1 中,您可以检查 HubConnection 的 State 属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-26
      • 2012-03-09
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2019-06-26
      相关资源
      最近更新 更多