Meirion Hughes
Meirion Hughes

Reputation: 26408

ASP.NET Core 1.0 WebSocket Setup?

I'm struggling to find an example to setup WebSockets in ASP.NET Core 1.0; they all seem to be for the previous versions of ASP.NET and some rely on properties that don't seem to exist under context (for me).

Main documentation only has a placeholder too. http://docs.asp.net/en/latest/

For example:

app.UseWebSockets();

app.Use(async (context, next) =>
{
    if (context.IsWebSocketRequest)
    {
        WebSocket webSocket = await context.AcceptWebSocketAsync();
        await EchoWebSocket(webSocket);
    }
    else
    {
        await next();
    }
});

Doesn't work because IsWebSocketRequest doesn't exist now. What is the correct approach in ASP.NET Core 1.0?

Upvotes: 14

Views: 5653

Answers (1)

Meirion Hughes
Meirion Hughes

Reputation: 26408

After some disassembly it looks like its been moved around a little; and there is a new WebSocketManager

app.UseWebSockets();

app.Use(async (context, next) =>
{
    var http = (HttpContext) context;

    if (http.WebSockets.IsWebSocketRequest)
    {
        WebSocket webSocket = await http.WebSockets.AcceptWebSocketAsync();
    }
});

Also turns out that because there was a compile error, it assumed context was of type RequestDelegate. After fixing the usage to context.WebSockets.IsWebSocketRequest it now knows that context is HttpContext

Upvotes: 13

Related Questions