如何从 API 控制器调用/调用集线器方法“DisconnectFromConversation”
枢纽实施
public class ChatHub : Hub
{
private readonly IConversationService \_converstaionService;
private readonly IMemberService \_converstaionUserService;
private readonly IMessageService \_messageService;
public ChatHub(IConversationService converstaionService,
IMemberService converstaionUserService, IMessageService messageService)
{
_converstaionService = converstaionService;
_converstaionUserService = converstaionUserService;
_messageService = messageService;
}
public async Task DisconnectFromConversation(Guid conversationId, Guid userId)
{
if (ConnectionMapping.TryGetValue(userId, out var connectionIds))
{
foreach (var connectionId in connectionIds)
{
await Groups.RemoveFromGroupAsync(connectionId, conversationId.ToString());
}
}
}
控制器实施
public class MemberController : ControllerBase
{
private readonly IMemberService \_memberService;
private readonly IConversationService \_conversationService;
private readonly IHubContext\<ChatHub\> \_hubContext;
public MemberController(IMemberService memberService, IConversationService conversationService, IHubContext<ChatHub> hubContext)
{
_memberService = memberService;
_conversationService = conversationService;
_hubContext = hubContext;
}
[HttpDelete("conversations/{conversationId}")]
public async Task<IActionResult> DeleteMember([FromBody]string userId, Guid conversationId)
{
var test = Request.Headers["connectionId"];
if (!Request.Headers.ContainsKey("User-Id"))
{
return BadRequest();
}
else if (await _conversationService.IsUserCreator(conversationId,
new Guid(Request.Headers["User-Id"]))
|| Request.Headers["User-Id"] == userId.ToString())
{
await _memberService.DeleteMemberAsync(conversationId, new Guid(userId));
//await _hubContext.Clients.All
.BrodacastMessage("DisconnectFromConversation", conversationId, userId);
await _hubContext.Clients.Client(test)
.SendAsync("DisconnectFromConversation", conversationId, userId);
return NoContent();
}
else
{
return Forbid();
}
}
}
我尝试通过下一种方式调用await _hubContext.Clients.All.BrodacastMessage("DisconnectFromConversation", conversationId, userId);
,但在调试模式下它不会触发集线器方法中的断点我也尝试过await _hubContext.Clients.Client(test).SendAsync("DisconnectFromConversation", conversationId, userId);
我正在考虑将此操作委托给客户端。但不幸的是我没有它(这是任务的要求之一)