Using WebSockets with ASP.NET Web API

后端 未结 5 1477
眼角桃花
眼角桃花 2020-12-02 14:52

What is the preferred method for using raw websockets in an ASP.NET Web API application?

We\'d like to use binary WebSockets on a couple of our inte

5条回答
  •  星月不相逢
    2020-12-02 15:17

    This is an older question, but I would like to add another answer to this.
    It turns out, you CAN use it, and I have no clue why they made it so "hidden". Would be nice if someone could explain to me what's wrong with this class, or if what I'm doing here is somehow "forbidden" or "bad design".

    If we look in the Microsoft.Web.WebSockets.WebSocketHandler, we find this public method:

    [EditorBrowsable(EditorBrowsableState.Never)]
    public Task ProcessWebSocketRequestAsync(AspNetWebSocketContext webSocketContext);
    

    This method is hidden from intellisense, but it's there, and can be called without compilation errors.
    We can use this method to get the task that we need to return in the AcceptWebSocketRequest method. Check this out:

    public class MyWebSocketHandler : WebSocketHandler
    {
        private static WebSocketCollection clients = new WebSocketCollection();
    
        public override void OnOpen()
        {
            clients.Add(this);
        }
    
        public override void OnMessage(string message)
        {
            Send("Echo: " + message);
        }
    }
    

    And then in my API controller:

    public class MessagingController : ApiController
    {
        public HttpResponseMessage Get()
        {
            var currentContext = HttpContext.Current;
            if (currentContext.IsWebSocketRequest ||
                currentContext.IsWebSocketRequestUpgrading)
            {
                currentContext.AcceptWebSocketRequest(ProcessWebsocketSession);
            }
    
            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
        }
    
        private Task ProcessWebsocketSession(AspNetWebSocketContext context)
        {
            var handler = new MyWebSocketHandler();
            var processTask = handler.ProcessWebSocketRequestAsync(context);
            return processTask;
        }
    }
    

    This works completely fine. OnMessage gets triggered, and echoes back to my JavaScript instantiated WebSocket...

提交回复
热议问题