【发布时间】:2020-12-05 19:11:50
【问题描述】:
我已经在我的 Angular 客户端和 asp.netcore webapi 上实现了 signalR。目前,当客户端连接到服务器时,我收到以下错误
WebSocket connection to 'ws://localhost:5000/notificationHub' failed: Error during WebSocket handshake: Unexpected response code: 307
谁能告诉我可能是什么问题。我已经在服务器端设置了 CORS。目前我正在为客户端使用端口 4021,因为我已经使用该端口为客户端提供服务。服务器在 5000 端口上可用
服务器代码
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.AddHostedService<DashboardHostedService>();
services.AddControllers();
services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins("http://localhost:4201");
}));
services.AddSignalR();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors("CorsPolicy");
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/notificationHub");
});
}
}
Angular 客户端
export class SignalrService {
private message$: Subject<Message>;
private connection: signalR.HubConnection;
constructor() {
this.message$ = new Subject<Message>();
this.connection = new signalR.HubConnectionBuilder()
.withUrl(environment.hubUrl, {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
this.connect();
}
private connect(): void {
if (this.connection.state === signalR.HubConnectionState.Disconnected) {
this.connection.start().catch(err => console.log(err));
}
}
}
【问题讨论】:
-
这能回答你的问题吗? SignalR CORS same origin policy?
-
嗨@Tom,关于这个案例的任何更新?
标签: angular asp.net-core signalr