14

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?

4
  • Given the lack of information around ASP.NET 5 at the moment and there is literally nothing of worth on google for more advanced questions I would rather the question stay to see if anyone actually knows how to do it. Beta or not if people are using it I would say its a valid question, although maybe it would be worth refactoring the title to reflect the beta number so it would at least become separate from the future questions on ASP.NET 5 if the framework is vastly different.
    – Grofit
    Commented Aug 19, 2015 at 15:13
  • ASP.NET 5 is still in beta, so you're asking for a tutorial on a moving target. And the current builds for Web Sockets in ASP.NET 5 don't seem to be ready, as the builds are failing.
    – mason
    Commented Aug 19, 2015 at 15:17
  • 1
    Well the the beta binaries are on NuGet. Beta generally means they're locked down and bug hunting. I've made it a specific coding problem now so hopefully that jumps though the SO hoops... Commented Aug 19, 2015 at 15:18
  • 1
    Not specifically relevant to your question, but I also had to map the websocket to a subpath for it to work, probably because it conflicted with MVC. app.Map("/WebSockets", wsApp => { wsApp.UseWebSockets(); wsApp.Use(/*...*/);
    – angularsen
    Commented Mar 19, 2016 at 23:01

1 Answer 1

13

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

1
  • I am trying to implement websockets in .net core 1.0 but not being able to find the packages that works with it. can you please share what packages did you use also What Client side should i use with react. here is a link to my question stackoverflow.com/questions/47534840/… Thanks Commented Nov 29, 2017 at 13:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.