How to connect to WebSocket through Controller?

Viewed 152

I am trying to connect to WebSocket through Controller as below using Postman, but isSocketRequest keeps false, what I missed?

  public class WebSocketController : ControllerBase
  {
    [HttpGet]
    [AllowAnonymous]
    public async Task Get()
    {
        var context = ControllerContext.HttpContext;

        var isSocketRequest = context.WebSockets.IsWebSocketRequest;

        Helper.SaveLog("WebSocketController: " + isSocketRequest);

        if (isSocketRequest)
        {
            WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
            context.Response.StatusCode = 200;
        }
        else
        {
            context.Response.StatusCode = 400;
        }
    }
1 Answers

You must add app.UseWebSockets(); in Configure() in Startup.cs. Also you shouldn't set StatusCode = 200;, otherwise client will throw error. Accepting the websocket is enough.

Related