Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
Meirion Hughes Avatar asked Aug 19 '15 14:08

Meirion Hughes


Video Answer


1 Answers

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

like image 52
Meirion Hughes Avatar answered Sep 20 '22 01:09

Meirion Hughes