有人知道 AspNetCore SignalR 与 AspNet SignalR 中的这段代码等效吗?
Task.Factory.StartNew(() =>
{
//// var clients = Hub.Clients<RealTimeNotificationHub>();
var connection = new HubConnectionContext("https://demohouse.go.ro:96/");
var notificationmessag = new AlertMessage();
notificationmessag.Content = "New message from " + device.Name + " <b>" +
text + " </b>";
notificationmessag.Title = alertType.Name;
var myHub = connection.CreateHubProxy("realTimeNotificationHub");
connection.Start().Wait();
object[] myData = { notificationmessag.Title, notificationmessag.Content };
myHub.Invoke("sendMessage", myData).Wait();
connection.Stop();
});
添加 Nuget 包 Microsoft.AspNetCore.SignalR.Client 并尝试以下代码。我冒昧地使用了您帖子中的数据并将其转换为 .Net Core 版本。
//I'm not really sure how your HUB route is configured, but this is the usual approach.
var connection = new HubConnectionBuilder()
.WithUrl("https://demohouse.go.ro:96/realTimeNotificationHub") //Make sure that the route is the same with your configured route for your HUB
.Build();
var notificationmessag = new AlertMessage();
notificationmessag.Content = "New message from " + device.Name + " <b>" +
text + " </b>";
notificationmessag.Title = alertType.Name;
object[] myData = { notificationmessag.Title, notificationmessag.Content };
connection.StartAsync().ContinueWith(task => {
if (task.IsFaulted)
{
//Do something if the connection failed
}
else
{
//if connection is successfull, do something
connection.InvokeAsync("sendMessage", myData);
}).Wait();
您可以使用不同的方法来执行异步任务。
注意:您的 Hub 还应该使用 SignalR 的 .Net Core 包 (Microsoft.AspNetCore.SignalR) 才能使其正常工作(根据我的经验)。
private HubConnection connection;
string url = "http://Server:port/Hub_Name";
connection = new HubConnectionBuilder()
.WithUrl(url)
.WithAutomaticReconnect()
.Build();
connection.StartAsync().ContinueWith(task => {
if (task.IsFaulted)
{
//Do something if the connection failed
}
else
{
//if connection is successfull, do something
connection.InvokeAsync("sendMessage", myData);
}).Wait();
}