【问题标题】:ASP.NET Core WebSocket failed during handshakeASP.NET Core WebSocket 在握手期间失败
【发布时间】:2017-03-23 15:38:51
【问题描述】:

我正在尝试使用 ASP.NET Core WebSocket,但是在 JavaScript 中 new WebSocket("ws://localhost:5702"); 时出现这样的错误:

WebSocket connection to 'ws://localhost:5702/' failed: Error during WebSocket handshake: Unexpected response code: 200

Startup.cs 中我的配置方法:

public void Configure(IApplicationBuilder app)
{
     app.UseDefaultFiles();

     app.UseStaticFiles();

     app.UseWebSockets();
     app.UseWebSocketHandler();
}

我的Middlewares\WebSocketMiddleware.cs:
WebSocketMiddleware.cs

有人知道吗?

谢谢。

【问题讨论】:

    标签: javascript c# asp.net .net websocket


    【解决方案1】:

    您遇到的行为是因为其他一些中间件 (UseStaticFiles) 正在向您的 websocket 客户端返回 200 OK 代码。

    为避免这种情况,请确保将 WebSocket 中间件放在 UseStaticFiles() 之前。就个人而言,我会把它放在顶部,如下所示:

        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(...);
        }
    

    【讨论】:

      猜你喜欢
      • 2017-05-09
      • 2020-07-09
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2016-03-15
      • 2011-04-07
      相关资源
      最近更新 更多