I am trying to remove a connectionId from a Group in Signalr. The method I want to call from the client (JS) is called UbsubscribeFromProject.
Here is the Hub file:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using OptTurnaroundApi.Repositories;
using OptTurnaroundApi.Services;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace OptTurnaroundApi.Hubs
{
[Authorize]
public class MyHub : Hub
{
private readonly IUserRepository _userRepository;
private readonly IAuthService _authService;
private readonly ILogger<MyHub> _logger;
public MyHub(IUserRepository userRepository, IAuthService authService, ILogger<MyHub> logger)
{
_userRepository = userRepository;
_authService = authService;
_logger = logger;
}
public async Task SubscribeToProject(string projectId)
{
var user = _userRepository.GetCurrentUser(true);
try
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"Project{projectId}");
}
catch (Exception ex)
{
_logger.LogWarning($"User {user.UserName} could not subscribe to project {projectId}: {ex.Message}");
}
}
public async Task UnsubscribeFromProject(string projectId)
{
var user = _userRepository.GetCurrentUser(true);
try
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Project{projectId}");
}
catch (Exception ex)
{
_logger.LogWarning($"User {user.UserName} could not unsubscribe project {projectId}: {ex.Message}");
}
}
public string GetConnectionId()
{
return Context.ConnectionId;
}
}
}
I am able to call the SubscribeToProject func开发者_如何学编程tion from the frontend, but when I try to call the UnsubscribeFromProject I am not even seeing that it is being sent in the Websockets window in the network tab for chrome developer tools.
I have no idea why it is not being called, when the code is clearly being run on the frontend (tried debugging to see that UnsubscribeFromProject is indeed called with defined parameters)
The function that is being triggered on the client is the following:
const subscribeToNewProject = useCallback(
({ previousProjectId, connection }) => {
// subscribe to new project when user changes project
if (
previousProjectId &&
connection &&
projectId &&
previousProjectId !== projectId
) {
// subscribe to a new project Id if the user changes project
connection.invoke("SubscribeToProject", projectId.toString());
connection.invoke(
"UnsubscribeFromProject",
previousProjectId.toString()
);
setPreviousProjectId(projectId);
}
},
[projectId]
);
精彩评论