我正在尝试将SignalR与ASP核心2.1和angular 7一起使用。
但是每当我尝试运行它时,都会在浏览器控制台中给我错误:
我只是遵循了实现ChatHub示例的基础知识,并尝试对其进行了更改,但没有修复,而当我搜索相同的错误时,我发现没有任何解决方案可以解决,因为每种解决方案都不适合我。
asp核心中的C#代码
public void ConfigureServices(IServiceCollection services)
{
// rest of the code
/////////////////////////
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build());
});
services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// rest of the code
/////////////////////////
app.UseCors(builder =>
builder.WithOrigins("https://localhost:44365", "https://localhost:5001", "http://localhost:4200", "http://localhost:5000").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseSignalR(route =>
{
route.MapHub<ChatHub>("/chathub");
});
}
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
角度服务中的打字稿代码
sendChatMessage(message: String) {
this._hubConnection.invoke('SendMessage', message);
}
private createConnection() {
this._hubConnection = new HubConnectionBuilder()
.withUrl('chathub',
{
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.configureLogging(signalR.LogLevel.Information)
.build();
}
private startConnection(){
this._hubConnection
.start()
.then(() => {
this.connectionIsEstablished = true;
console.log('Hub connection started');
this.connectionEstablished.emit(true);
})
.catch(err => {
console.log('Error while establishing connection ',err);
});
}