Reputation: 1214
I'm trying to use ASP.NET Core WebSocket, but got an error like this when new WebSocket("ws://localhost:5702");
in JavaScript:
WebSocket connection to 'ws://localhost:5702/' failed: Error during WebSocket handshake: Unexpected response code: 200
My Configure method in Startup.cs
:
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseWebSockets();
app.UseWebSocketHandler();
}
My Middlewares\WebSocketMiddleware.cs
:
WebSocketMiddleware.cs
Does anyone know?
Thank you.
Upvotes: 3
Views: 9034
Reputation: 2172
The behaviour you are experiencing is because some other middleware (UseStaticFiles) is returning a 200 OK code to your websocket client.
To avoid this, make sure to place your WebSocket middleware before UseStaticFiles(). Personally, I'd put it at the top, like so:
public void Configure(IApplicationBuilder app)
{
//first handle any websocket requests
app.UseWebSockets();
app.UseWebSocketHandler();
//now handle other requests (default, static files, mvc actions, ...)
app.UseDefaultFiles();
app.UseStaticFiles();
//app.UseMvc(...);
}
Upvotes: 6