【问题标题】:Invocation canceled due to the underlying connection being closed. Flutter and .netcore 3.1由于底层连接被关闭,调用被取消。 Flutter 和 .net 核心 3.1
【发布时间】:2021-11-09 13:19:47
【问题描述】:

我尝试在 connection.start 之后将我的信号器集线器与颤振客户端连接,然后我尝试调用它的方法,它给出的错误是“由于底层连接被关闭而取消调用”。

我尝试在不同的 iis 服务器上运行它,结果相同。 有人可以指导我吗

Flutter 客户端代码在这里

Future<void> signalr() async {
    const serverUrl = "<serverurl>";

// Creates the connection by using the HubConnectionBuilder.
    final hubConnection = HubConnectionBuilder().withUrl(serverUrl).build();
// When the connection is closed, print out a message to the console.
//     final hubConnection.onclose( (error) => print("Connection Closed"));
    hubConnection.serverTimeoutInMilliseconds = 1000000;

    await hubConnection.start();
    hubConnection.onclose(({error}) {
    });

    final result = await hubConnection.invoke("joinRoom", args: ['1']);

    print('Result: $result');
    hubConnection.on('RecieveMessage', (message) {
      print('sasta123'+ message.toString());
    });
  }

startup.cs 在这里

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddControllers()
                .AddNewtonsoftJson(options =>
                 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v2", new OpenApiInfo
                {

                    Version = "v2",
                    Title = "AM_ChatAPI",
                    Description = "AM_ChatAPI-v2",
                    TermsOfService = new Uri("https://www.adamjeelife.com"),
                    Contact = new OpenApiContact
                    {
                        Name = "AdamjeeLife",
                        Email = string.Empty,
                        Url = new Uri(""),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri(""),
                    }
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                          new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "Bearer"
                                }
                            },
                            new string[] {}

                    }
                });
                c.ResolveConflictingActions(apiDesc => apiDesc.First());
            });

            //Step2


            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })
          .AddJwtBearer(options =>
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuer = true,
                  ValidateAudience = true,
                  ValidateLifetime = true,//if False then that the expired token is considered valid
                  ValidateIssuerSigningKey = true,
                  ValidIssuer = Configuration["Jwt:Issuer"],
                  ValidAudience = Configuration["Jwt:Issuer"],
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))//key must be min 16 chars
              };
              options.Events = new JwtBearerEvents
              {
                  OnAuthenticationFailed = c =>
                  {
                      if (c.Exception.GetType() == typeof(SecurityTokenExpiredException))
                      {

                          c.Response.StatusCode = 401;
                          c.Response.ContentType = "application/json";
                          var result = JsonConvert.SerializeObject(new string("Token Expired"));
                          return c.Response.WriteAsync(result);
                      }
                      else
                      {
                          return Task.CompletedTask;
                      }
                  },
              };
          });
            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(5);
            }).AddJsonProtocol(options => {
                options.PayloadSerializerOptions.PropertyNamingPolicy = null; 
     
     });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseFileServer();
            app.UseStaticFiles();
            //  loggerFactory.AddSerilog();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v2/swagger.json", "CoreApp APIv2");
            });
            app.UseHttpsRedirection();
            app.UseRouting();
            //app.UseRouting();
            //global cors policy
            app.UseCors(x => x
              .AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chathub", options =>
                {
                    options.Transports =
                        HttpTransportType.WebSockets |
                        HttpTransportType.LongPolling;
                });
            });
        }
    }
    ```

【问题讨论】:

    标签: flutter signalr asp.net-core-3.1 signalr-hub


    【解决方案1】:

    我通过降低我的 entityframewok 核心版本来修复

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多