How to use websocket in asp.net core mvc controllers?

I want for example in real time to display changes in user data (his userName and Email). On the Internet I found many instructions on how to implement websocket through the creation of Middleware. I would like to use my usual controllers, where there are attributes like [Authorize] , getting services through Dependency Injection and so on.

  • About SignalR heard? - Alex78191
  • one
    @ Alex78191 he's in alpha, I don’t think it’s a good idea to use it - mirypoko
  • You can make your IActionResult where to hang in ExecuteResultAsync and at this time send as many as you want to the socket. I did the implementation of server sent events without middleware for the same reason - the controller must decide whether the user is allowed to connect and where. - vitidev

1 answer 1

I also wondered about this idea and implemented it on the basis of the main Middleware documentation.

 [Route("ws/[controller]/[action]")] [Authorize(Roles = TechnicalRoles.HopProgram)] public class HopController : Controller { private readonly ApplicationDbContext _context; public ChopController(ApplicationDbContext context) { _context = context; } /// <summary> /// Нужно для коннекта клиента /// </summary> /// <returns></returns> [HttpGet] public async Task Connect() { if (HttpContext.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); await Echo(HttpContext, webSocket); } else { HttpContext.Response.StatusCode = 400; } } // Тест возврата полученных сообщений private async Task Echo(HttpContext context, WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } } 

Connect to this good at ws: // localhost: port / ws / hop / connect