无法在信号器OnDisconnected方法中调用web api控制器

时间:2017-06-02 06:13:30

标签: asp.net-mvc signalr

我有一个带有信号器的mvc web应用程序,我想更新已发布的web api中的表。

调用web api控制器以使Onconnected方法中的用户正常工作:

public override async Task OnConnected()
{ 
    var users = await _client.GetAsync("chats/users");
    Clients.All.userConnected();
}

但是当我将代码放在OnDisconnected方法中时,它会给我一个错误:

public override async Task OnDisconnected(bool stopCalled)
{
     var users = await _client.GetAsync("chats/users");
}

为什么会这样?这是整个Hub代码:

private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
private HttpClient _client;

public ChatHub()
{
    AccessDelegatingHandler handler = new AccessDelegatingHandler();

    _client = HttpClientFactory.Create(handler);
    _client.BaseAddress = new Uri(ClsConfig.GetConfiguration().APIBaseAddress);
}

// Send new message to group chat.
public static void SendGroupMessage(MessageDetailModel messageDetail)
{
    hubContext.Clients.All.newGroupMessageReceived(messageDetail);
}

public override async Task OnConnected()
{ 
    var users = await _client.GetAsync("chats/users");

    Clients.All.userConnected();
}

public override Task OnReconnected()
{
    return base.OnReconnected();
}

public override async Task OnDisconnected(bool stopCalled)
{
    var users = await _client.GetAsync("chats/users");
}

修改 我发现,当我在var user = Context.User.Identity;方法中放置OnDisconnected时,用户为IsAuthenticated = true但是当我在AccessDelegatingHandler类中放置一个断点时var identity = (ClaimsIdentity)HttpContext.Current.User.Identity;行给出错误并且是IsAuthenticated = false

1 个答案:

答案 0 :(得分:0)

当onDisconnected事件触发时,您可能已经断开连接,并且无法保证您的代码将运行(它是Signalr的已知问题)您是否也在监视客户端或服务器中的onDisconnected?看起来你正试图从服务器处理它,你应该从客户端处理它。

这个链接应该有助于理解为什么会这样。

https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#clientdisconnect