使用 CentOS 和 Nginx 的 blazor 上的 websocket 问题

websocket issue on blazor with CentOS and Nginx

我正在尝试使用 CentOS 将我的 blazor 应用程序(服务器端)部署到我的 VPS 中。

部署顺利,我可以访问我的网站,但在控制台中我看到以下错误:

blazor.server.js:1 WebSocket connection to 'wss://website.com/_blazor?id=bMDvWwyNa5R5y9KsTVUS6A' failed: 
(anonymous) @ blazor.server.js:1
blazor.server.js:1 [2021-05-01T07:33:36.170Z] Error: Failed to start the transport 'WebSockets': Error: There was an error with the transport.
e.log @ blazor.server.js:1
/_blazor?id=l_DDVIXzIu1Ro3zd9stUsA&_=1619854490093:1 Failed to load resource: the server responded with a status of 504 ()
blazor.server.js:1 [2021-05-01T07:35:50.195Z] Error: Connection disconnected with error 'Error'.

而且我不知道如何处理它们。

据我所知,websocket/signalR 没有打开,这意味着一旦加载网站,连接就会“切断”这里的问题是 blazor 每分钟都会调用一次,所以我得到一个消息说 attempting to reconnect to the server 并且它做到了。但是该网站无法使用 5 秒左右。

为了解决这个问题,我尝试了网上看到的多种解决方案:

在项目中:设置了services.AddSignalR()app.UseWebSockets(),但没用。

我也认为它可能是 nginx(并且可能是)然后我发现了这个: https://www.nginx.com/blog/websocket-nginx/https://docs.microsoft.com/en-us/aspnet/core/blazor/host-and-deploy/server?view=aspnetcore-5.0#linux-with-nginx

但它似乎不起作用:

map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

server {
    server_name website.com;

    location / {
        proxy_pass         http://localhost:5201;
        proxy_http_version 1.1; # added from ms documentation
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection $http_upgrade;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    listen 443 http2 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

编辑: 我在 nginx 文件中也有这个

server{
if ($host = website.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    server_name website.com ;
    listen 80 ;
    return 404;
}

EDIT2: 我在 nginx 上运行 1.20 版本

知道连接的哪一部分可能是错误的吗?

谢谢。

发现问题,在proxy_set_header Connection $http_upgrade;

更改为: proxy_set_header Connection "upgrade";

不确定为什么在对值进行硬编码时会起作用,但确实如此。

感谢您提供这个简单的解决方案!这对我的情况有所帮助,我的配置如下所示并且非常有效(debian 10、nginx 1.14、.net 6、blazor):

location / {
       proxy_pass http://127.0.0.1:5000;
       proxy_http_version 1.1;
       proxy_set_header   Upgrade $http_upgrade;
       proxy_set_header   Connection keep-alive;
       proxy_set_header   Connection "Upgrade";
       proxy_set_header   Host $host;
       proxy_cache_bypass $http_upgrade;
       proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header   X-Forwarded-Proto $scheme;
    }