我正在尝试从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#方面提供的任何建议。
答案 0 :(得分:1)
您需要将前端的网址更改为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)); });