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