来自 TypeScript 的 signalR 集线器连接失败
failed signalR hub connection from TypeScript
我正在尝试从 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 中有以下代码。
fyi:我添加了 /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!");
});
});
}
}
}
当我启动我的核心项目时,它在 App URL http://localhost:55883/
以及 SLL https://localhost:44311/
下的 IIS 中运行。
我似乎无法初始化 HUB 连接,也不知道我的问题出在哪里:
在 negotiate
请求上请求 headers:
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# 方面提供的任何建议。
您需要将前端的 url 更改为 https
,例如:
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));
});
我正在尝试从 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 中有以下代码。
fyi:我添加了 /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!");
});
});
}
}
}
当我启动我的核心项目时,它在 App URL http://localhost:55883/
以及 SLL https://localhost:44311/
下的 IIS 中运行。
我似乎无法初始化 HUB 连接,也不知道我的问题出在哪里:
在 negotiate
请求上请求 headers:
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# 方面提供的任何建议。
您需要将前端的 url 更改为 https
,例如:
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)); });