代码之家  ›  专栏  ›  技术社区  ›  racamp101

.Net Core 2信号器alpha2集线器不工作

  •  2
  • racamp101  · 技术社区  · 7 年前

    我有一个重大问题无法解决。我与jwt auth有一个.net core 2项目,并试图让基本的信号集线器测试正常工作。来自客户端的连接似乎正常工作,但连接立即中断,代码为204。

    我的集线器运行在前端UI之外的另一个URL上,因此涉及CORS。

    **我删除了真实的密钥和我的项目名称

    这是客户端控制台的输出:

    console

    这是我的启动代码:

    public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
            services.Configure<DiAssemblies>(Configuration.GetSection("DiAssemblies"));
            services.Configure<StripeSettings>(Configuration.GetSection("Stripe"));
            services.Configure<AzureStorageSettings>(Configuration.GetSection("AzureStorageSettings"));
    
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    x => x.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });
    
    
            services.AddCors();
    
            services.AddIdentity<testApp.Identity.ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<testApp.Identity.Context>()
            .AddDefaultTokenProviders();
    
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    
    
            })
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
    
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("authkeyasdfasdfasdfsadfasdfda")),
                        ValidIssuer = "https://testApp.com/",
                        ValidAudience = "https://testApp.com/",
    
                    };
                    options.Events = new JwtBearerEvents
                    {
    
                        OnAuthenticationFailed = context =>
                        {
                            Debug.WriteLine("Auth issue");
                            Debug.WriteLine(context.Exception);
                            return Task.CompletedTask;
                        },
    
                        OnMessageReceived = context =>
                        {
                            if (!context.Request.Headers.ContainsKey("Authorization") && !string.IsNullOrEmpty(context.Request.Query["authToken"]))
                            {
                                context.Request.Headers.Add("Authorization", context.Request.Query["authToken"]);
                            }
                            return Task.CompletedTask;
                        },
                        OnChallenge = context =>
                        {
                            Debug.WriteLine("Auth issue");
                            Debug.WriteLine(context.Error);
                            Debug.WriteLine(context.ErrorDescription);
                            return Task.CompletedTask;
                        }
                    };
                });
    
            services.AddMemoryCache();
    
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
    
            services.AddSockets();
            services.AddSignalRCore();
    
            var builder = new ContainerBuilder();
    
            // Register dependencies, populate the services from
            // the collection, and build the container. If you want
            // to dispose of the container at the end of the app,
            // be sure to keep a reference to it as a property or field.
            //builder.RegisterType<MyType>().As<IMyType>();
            builder.Populate(services);
            var diHelper = new DiHelper();
            var diAssemblies = Configuration.GetValue<string>("DiAssemblies:List");
            var assemblies = diHelper.GetAssemblies(diAssemblies.Split(',').ToList());
          //  Console.Write(diAssemblies);
            builder.RegisterAssemblyModules(assemblies);
    
            ApplicationContainer = builder.Build();
    
            //foreach(var assembly in assemblies)
            //    services.AddMvc().AddApplicationPart(assembly).AddControllersAsServices();
    
            // Create the IServiceProvider based on the container.
            return new AutofacServiceProvider(ApplicationContainer);
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseCors(
                options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
            );
    
    
            app.UseAuthentication();
    
    
            app.UseMvc();
    
            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("chat");
            });
        }
    }
    

    我的中心(任何方法的断点都不会被击中)

    public class ChatHub : Hub
        {
            public ChatHub()
            {
                var t = 0;
            }
    
    
            public override async Task OnConnectedAsync()
            {
                await Clients.Client(Context.ConnectionId).InvokeAsync("send", "connection made");
    
                await base.OnConnectedAsync();
            }
    
            public Task Send(string message)
            { 
                return Clients.All.InvokeAsync("send", message); 
            }
        }
    

    客户端javascript:

    <script>
          window.connection;
          window.connection = new signalR.HubConnection("https://localhost:44367/chat?authToken=" + 'bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.yyJzdWIiOiJhYzNkMTU3OC05YjU5LTRmNzQtOWMxYi01MWZlYjk2YmQ4YzEiLCJqdGkiOiJidnRlc3QxIiwiZXhwIjoxTYI2NjY1OTM3LCJpc3MiOiJodHRwczovL2Jpc3ZpbmUuY29tLyIsImF1ZCI6Imh0dHBzOi1vYmlzdmluZS5jb20vIn0.GxycqmyVsdHkW3M5yRH7arGkR3K-jAE2zrPrgoJnh-M', 
                                    { transport: signalR.TransportType.LongPolling });
    
          window.connection.on('send', function(message) {
            alert(message);
          });
    
    
          window.connection.start().then(function() {
            console.log("SignalR Connected: Chat");
            window.connection.invoke('send',"hi").then(function (chats) {
              console.log(chats);
            });
          }, function () {
    
          });
        </script>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   racamp101    7 年前

    我知道这一定很容易,但希望如果其他人遇到这件事,这也能帮助他们。

    拔出头发后,我后退了一步,注意到日志显示发现了集线器,我注意到隐藏了几行,另一个mvc控制器也在被调用。找到控制器后,我注意到它没有属性[路由(“api/[控制器]”)。

    加上这个,一切都开始工作了!似乎每个控制器都需要至少设置一个路由,否则mvc将在信号机有机会完全启动之前接听电话。