ClientHubController.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.AspNetCore.SignalR;
  4. using OASystem.API.OAMethodLib.Hub.HubClients;
  5. using OASystem.API.OAMethodLib.Hub.Hubs;
  6. using OASystem.API.OAMethodLib.SignalR.Hubs;
  7. namespace OASystem.API.Controllers
  8. {
  9. /// <summary>
  10. /// 消息客户端
  11. /// </summary>
  12. [Route("api/[controller]/[action]")]
  13. public class ClientHubController : ControllerBase
  14. {
  15. private readonly ILogger<ClientHubController> _logger;
  16. private readonly IHubContext<ChatHub, IChatClient> _hubContext;
  17. public ClientHubController(ILogger<ClientHubController> logger, IHubContext<ChatHub, IChatClient> hubContext )
  18. {
  19. _logger = logger;
  20. _hubContext = hubContext;
  21. }
  22. /// <summary>
  23. /// 获取所有的用户
  24. /// </summary>
  25. /// <returns></returns>
  26. [HttpGet("GetAllUserIds", Name = "GetAllUserIds")]
  27. public List<UserModel> GetAllUserIds()
  28. {
  29. return UserStore.OnlineUser;
  30. }
  31. /// <summary>
  32. /// 发送消息给客户端
  33. /// </summary>
  34. /// <param name="userid"></param>
  35. /// <param name="date"></param>
  36. /// <param name="hubContext"></param>
  37. /// <returns></returns>
  38. [HttpPost("SendAllUserMessage", Name = "SendAllUserMessage")]
  39. public async Task<IActionResult> SendAllUserMessage( string msg)
  40. {
  41. await _hubContext.Clients.All.SendAll(msg);
  42. return Ok("Send Successful!");
  43. }
  44. /// <summary>
  45. /// 发送指定的消息给指定的客户端
  46. /// </summary>
  47. /// <param name="userid"></param>
  48. /// <param name="date"></param>
  49. /// <param name="hubContext"></param>
  50. /// <returns></returns>
  51. [HttpPost("SendCustomUserMessage", Name = "SendCustomUserMessage")]
  52. public async Task<IActionResult> SendCustomUserMessage(int userid,string date )
  53. {
  54. string connId = string.Empty;
  55. UserModel user = UserStore.OnlineUser.Where(it => it.UserId == userid).FirstOrDefault();
  56. if (user != null)
  57. {
  58. connId = user.ConnectionId;
  59. }
  60. await _hubContext.Clients.Client(connId).SendCustomUserMessage(date);
  61. return Ok("Send Successful!");
  62. }
  63. }
  64. }