【问题标题】:failed signalR hub connection from TypeScript来自 TypeScript 的 signalR 集线器连接失败
【发布时间】:2020-06-22 20:33:32
【问题描述】:

我正在尝试从 TypeScript 初始化与 Core 3.1 SignalR Hub 的连接。但是,我的前端 /negotiate 请求在它最终失败之前等待了相当长的一段时间。

我的 Angular 服务是 notification.service.ts -

import { Injectable } from '@angular/core';
import * as signalr from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  private hubConnection: signalr.HubConnection;

  public startConnection = () => {
    this.hubConnection = new signalr.HubConnectionBuilder()
                            .withUrl('http://localhost:44311/hub')
                            .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch((err) => console.log(`Error while starting connection: ${err}`));
  }
  constructor() { }
}

登录应用程序后立即调用:

this.notificationService.startConnection();

在 Core 3.1 服务器端,我的 Startup.cs 中有以下代码。 仅供参考:我添加了/hub 路由,还配置了CORS 以接受来自localhost:4200 的请求

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NotificationHub.Hubs;
namespace NotificationHub
{
    public class Startup
    {
        readonly string MyAllowedSpecificOrigins = "_myAllowedSpecificOrigins";

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowedSpecificOrigins,
                                  builder => {
                                      builder.WithOrigins("https://localhost:4200");                                                                          
                                  }
                                  );
            });
            services.AddSignalR();
        }

        
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseCors(MyAllowedSpecificOrigins);

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<Notifications>("/hub");      
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello Web World!");
                });
            });
        }
    }
}

当我启动我的 Core 项目时,它在 IIS 中的 App URL http://localhost:55883/ 以及 SLL https://localhost:44311/ 下运行。

我似乎无法初始化 HUB 连接,也不知道我的问题出在哪里:

negotiate 请求上的请求标头:

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,es-CO;q=0.8,es;q=0.7
Access-Control-Request-Headers: x-requested-with
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:44311
Origin: http://localhost:4200

感谢您愿意在 TypeScript 或 C# 方面提供的任何建议。

【问题讨论】:

标签: signalr signalr-hub


【解决方案1】:

需要把前端的url改成httpslike:

import { Injectable } from '@angular/core';
import * as signalr from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class NotificationService {

  private hubConnection: signalr.HubConnection;

  public startConnection = () => {
    this.hubConnection = new signalr.HubConnectionBuilder()
                            .withUrl('https://localhost:44311/hub')
                            .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch((err) => console.log(`Error while starting connection: ${err}`));
  }
  constructor() { }
}

然后在服务器端正确实现CORS

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多