我正在使用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.Client
v1.0.0-preview1-final
答案 0 :(得分:4)
没有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
}
}
用法:
public async Task SendMessage(Msg model)
{
await StartIfNeededAsync();
await _connection.SendAsync("Send", model);
}
答案 1 :(得分:0)
至少在.NET Core 2.1中,您可以检查HubConnection的State
属性:
if (_connection.State == HubConnectionState.Disconnected) {
await _connection.StartAsync();
}