Asp.net core 5.0 - signalr 和 cloudfare 问题导致 524 状态代码

发布于 2025-01-17 08:16:21 字数 4678 浏览 0 评论 0原文

我有一个问题,我使用 nginx 是我的 Web 应用程序的 Web 服务器,

我使用 signalR 从 Web 应用程序到我的服务器有 1 个连接,但连接通常会丢失连接,并且 cloudfare 返回 524 错误状态代码

任何人都可以解决此问题

更新:我已经修复了这个问题,我将 proxy_pass 从 localhost 配置为 127.0.0.1,这解决了我的问题

但是我还有另一个问题,当我查看来自我的网站的请求时,

这是我的代码

public void ConfigureServices(IServiceCollection services){

            //adding swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApp1", Version = "v1" });
            });

            // Adding Authentication  
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })


            // Adding Jwt Bearer  
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    //ValidAudience = Configuration["JWT:ValidAudience"],
                    //ValidIssuer = Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])),
                    RequireExpirationTime = true,
                };
            });
            //Add mysql connection
            services.AddScoped<MySqlConnection>((provider) =>
            {
                var connection = Configuration.GetConnectionString("MySql");
                return new MySqlConnection(connection);
            });

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:4200", "http://localhost:3000")
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .SetIsOriginAllowed((x) => true)
                          .AllowCredentials();

            }));

            //add signalR
            services.AddSignalR(option =>
            {
                
            })
                 .AddJsonProtocol(options =>
                 {
                     options.PayloadSerializerOptions.Converters
                        .Add(new JsonStringEnumConverter());
                     options.PayloadSerializerOptions.IgnoreNullValues = true;
                 }); ;
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp";
            });

            services.AddControllers()
                        .AddJsonOptions(opts =>
                        {
                            var enumConverter = new JsonStringEnumConverter();
                            opts.JsonSerializerOptions.Converters.Add(enumConverter);
                            opts.JsonSerializerOptions.IgnoreNullValues = true;
                        });
        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseSpaStaticFiles();


            // Make sure the CORS middleware is ahead of SignalR.
            app.UseRouting();

            app.UseAuthentication();
            app
             .UseCors("MyPolicy");


            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
                            "WebApp1 v1"));
            app.UseAuthorization();
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

            });
            app.UseEndpoints(endpoints =>
            {
                
                endpoints.MapHub<NotificationHub>("notify");
                endpoints.MapHub<MsgHub>("msg");
                endpoints.MapControllers();
            });
        }

我看到了 signalR 客户端的 2 个请求

https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ (POST) 状态代码 200

https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ&_=1648545303996 (GET) 状态代码 404

如何修复最后一个请求,不知道为什么服务器返回404

I have a problem, I use nginx is my web server of web application

I have 1 connection from web application to my server by using signalR, but connection usually lost connection and cloudfare return 524 error status code

Can anyone have solution for this problem

Update : I have fix that, I config proxy_pass from localhost to 127.0.0.1 and this reslove my prolem

But I have another problem, when I view request from my website

this is my code

public void ConfigureServices(IServiceCollection services){

            //adding swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApp1", Version = "v1" });
            });

            // Adding Authentication  
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })


            // Adding Jwt Bearer  
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    //ValidAudience = Configuration["JWT:ValidAudience"],
                    //ValidIssuer = Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])),
                    RequireExpirationTime = true,
                };
            });
            //Add mysql connection
            services.AddScoped<MySqlConnection>((provider) =>
            {
                var connection = Configuration.GetConnectionString("MySql");
                return new MySqlConnection(connection);
            });

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:4200", "http://localhost:3000")
                          .AllowAnyHeader()
                          .AllowAnyMethod()
                          .SetIsOriginAllowed((x) => true)
                          .AllowCredentials();

            }));

            //add signalR
            services.AddSignalR(option =>
            {
                
            })
                 .AddJsonProtocol(options =>
                 {
                     options.PayloadSerializerOptions.Converters
                        .Add(new JsonStringEnumConverter());
                     options.PayloadSerializerOptions.IgnoreNullValues = true;
                 }); ;
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp";
            });

            services.AddControllers()
                        .AddJsonOptions(opts =>
                        {
                            var enumConverter = new JsonStringEnumConverter();
                            opts.JsonSerializerOptions.Converters.Add(enumConverter);
                            opts.JsonSerializerOptions.IgnoreNullValues = true;
                        });
        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseSpaStaticFiles();


            // Make sure the CORS middleware is ahead of SignalR.
            app.UseRouting();

            app.UseAuthentication();
            app
             .UseCors("MyPolicy");


            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
                            "WebApp1 v1"));
            app.UseAuthorization();
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

            });
            app.UseEndpoints(endpoints =>
            {
                
                endpoints.MapHub<NotificationHub>("notify");
                endpoints.MapHub<MsgHub>("msg");
                endpoints.MapControllers();
            });
        }

I have saw 2 request of signalR client

https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ (POST) status code 200

https://****/notify?id=eTHEGY6Ae9_I2gSthLUcSQ&_=1648545303996 (GET) status code 404

How to fix last request, I don't know why server return 404

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文