3

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.

1 Answer 1

6

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(...); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.