angular - WebSocket 连接到“ws://localhost:5000/notificationHub”失败:WebSocket 握手期间出错:意外响应代码:307
问题描述
我已经在我的角度客户端和 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");
});
}
}
角客户端
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 集线器服务器似乎通过 HTTP (http://localhost:5000) 和 HTTPS (https://localhost:5001) 侦听和响应,并且您将应用程序配置为重定向 HTTP通过UseHttpsRedirection
在Startup
类中调用对 HTTPS 的请求。
如果您.withUrl("http://localhost:5000/notificationHub")
在 Angular 客户端指定 URL,这将导致问题。
要修复它,您可以尝试修改代码以使用 HTTPS URL。
.withUrl("https://localhost:5001/notificationHub", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
app.UseHttpsRedirection();
或者不通过从类Configure
中的方法中删除来强制使用 HTTPS Startup
。
推荐阅读
- r - 如何使用ggplot包含每个日期的刻度?
- arrays - 为列表列表中的每个唯一值分配一个数字
- mysql - 如何将实体映射到已经使用 Doctrine/Symfony5 创建的数据库?
- python - 在 Azure ML Notebook 中的超参数调整(超驱动)期间为子运行提供交互式登录
- android - 重启后自动运行服务
- python - Squish for Windows 不断检查整个应用程序窗口
- java - 如何使用适用于 java 11 的 gradle shadowJar 创建 jar 文件
- javascript - 如何隐藏表格中所有带有 HELLO 字样的行。如果 WORLD 不等于 javascript 中的 WORLD
- python - 我们如何在 django 中创建通用 API?
- python - 提取 xml 中的第一个元素 - 使用 xxx.find() 会导致非类型错误?