How to setup Websocket in Blazor Server?

35 Views Asked by At

I'm trying to create a WebSocket Server in my Blazor Server application, here it is my Program.cs:

...
    app.Use(async (context, next) =>
    {
        if (context.Request.Path == "/ws")
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                var webSocketHandler = context.RequestServices.GetRequiredService<IWebSocketHandler>();
                await webSocketHandler.HandleWebSocketAsync(context, webSocket);
            }
            else
            {
                context.Response.StatusCode = 400;
            }
        }
        else
        {
            await next();
        }
    });
    var webSocketOptions = new WebSocketOptions()
    {
        KeepAliveInterval = TimeSpan.FromSeconds(120),
    
    };
    
    app.UseWebSockets(webSocketOptions);
    
    ...

I am trying to test it using the WebSocketClient chrome extension. However, the connection request is blocked because context.WebSockets.IsWebSocketRequest is false!

I enabled allow-insecure-localhost and also ran dotnet dev-certs https --trust... I tried changing the port in the launchSettings.json; all the same result

2

There are 2 best solutions below

2
MIP On
0
Ace On

The app.UseWebSockets(webSocketOptions); should occur before the verification of conditions and Map.