c# - Angular 7 与 SignalR Hub 的连接失败
问题描述
尝试在我的服务器中编写集线器以向客户端广播通知
在我的服务器中: 1 - 安装了 nuget。2 - 使用 app.MapSignalR() 创建 Startup.cs;3 - 创建集线器:
[HubName("NotificationHub")]
public class NotificationHub : Hub
{
// required to let the Hub to be called from other server-side classes/controllers, using static methods
private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
// Send the data to all clients (may be called from client JS)
public void GetNotifications()
{
Clients.All.GetNotifications();
}
// Send the data to all clients (may be called from server C#)
public static void GetNotificationsStatic()
{
hubContext.Clients.All.GetNotifications();
}
}
4 - 使用获取和添加通知创建控制器。
在我的客户中:遵循本指南:https ://medium.com/@ghanshyamshukla/implementation-of-signalr-in-angular-5-app-with-asp-net-web-api-2-0-f09672817d4d (在我的 angular.json 而不是 '../node_modules..' 我已固定为 './node_modules..'
这是我的连接功能:
connectToSignalRHub() {
const signalRServerEndPoint = environment.baseURL;
this.connection = $.hubConnection(signalRServerEndPoint);
this.proxy = this.connection.createHubProxy('notificationHub');
this.proxy.on('messageReceived', () => {
console.log('new notifications');
});
this.connection.start().done((data: any) => {
console.log('Connected to Notification Hub');
}).catch((error: any) => {
console.log('Notification Hub error -> ' + error);
});
}
然后当我运行我的应用程序时,
尝试连接时this.connection.start()
我进入错误部分并出现错误:
错误:协商请求期间出错。在 Object.error (jquery.signalR.min.js:9)
我在控制台中看到了这个错误:
从源“ http :// ”访问“ https://localhost:44328/signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1563949114481 ”处的XMLHttpRequest localhost:8083 '已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
不用说我已经为我的应用启用了 CORS
解决方案
花了我几个小时,但我终于让它结合使用 http 和 https,以及删除/
端口号后面的尾随!
在 startup.cs 的 ConfigureServices 方法中
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}
));
services.AddSignalR();
在 startup.cs 的 Configure 方法中
app.UseCors("CorsPolicy");
app.UseSignalR(routes => routes.MapHub<NotifyHub>("/notify"));
客户端js:
const connection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:44394/notify')
.configureLogging(signalR.LogLevel.Debug)
.build();
connection.start().then(() => {
console.log('Connected!');
}).catch((err) => {
return console.error(err.toString());
});
可能还有其他成功的组合,但感觉就像我尝试了每一个组合,但当它最终奏效时,我还没有准备好继续尝试……</p>
推荐阅读
- javascript - 从选择元素中选择选项时触发更改事件
- java - 如何在基于 Docker 映像的 java:8-jdk-alpine 中使 curl 可用并保持映像干净?
- python - 如何从串口读取响应
- css - 在 Polymer 中使用 HTML-Tag 中的属性
- android - 片段的 startActivityForResult() 替代方案(通过片段完成任务并将结果传递给片段)
- c - 来自 C 的 Cython 将无符号字符数组传递给 Python
- arrays - VHDL - 同时添加大型 2D 阵列。这个的语法是什么
- macros - 如何在SAS中屏蔽此字符串中的所有字符
- javascript - Cordova Config 中的 errorUrl 无法在 Android 上运行
- ios - 收到带有数据的远程通知时激活 iOS 应用程序