我正在尝试读取组件中的通知,但推送后没有任何反应。 [A.Razor] 将我的 HubConnection 调用到 SendAsync,它调用它但是在我的其他组件上 [MainLayout.razor] 我什么也没得到。
到目前为止我的 A.razor :
private HubConnection? hubConnection;
public bool IsConnected =>
hubConnection?.State == HubConnectionState.Connected;
protected override async Task OnInitializedAsync()
{
if (hubConnection is null)
{
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"))
.Build();
await hubConnection.StartAsync();
}
listCode = await CodeService.GetCodeAccesAsync();
}
private async Task AddLign()
{
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", "userInput", "messageInput");
}
await OnInitializedAsync();
}
我的中心:
public class SignalRHub : Hub
{
//appelle depuis le js
public async Task SendMessage(string user, string msg)
{
await Clients.All.SendAsync("ReceiveMessage", user, msg, DateTime.Now.ToShortTimeString());
}
public async Task SendList()
{
await Clients.All.SendAsync("ReceiveMessage", new List<int>{ 1,2});
}
}
然后在我的 MainLayout.razor 中
private HubConnection? hubConnection;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub"))
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
string encodedMsg = $"{user}: {message}";
AllNotificationMessages.Add(new NotificationModel("Mon Titre"));
currentMessages = AllNotificationMessages.Where(elem => elem.Id != myMsg.Id).ToList();
StateHasChanged();
});
await hubConnection.StartAsync();
}
在Program.cs中
builder.Services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
//builder.Services.AddSignalRCore();
builder.Services.AddSignalR();
app.MapHub<SignalRHub>("/chatHub");`
为什么我没有收到通知?我使用的是 blazor 服务器应用程序,我已将其迁移到 .NET 8。
我们需要安装
Newtonsoft.Json
包,确保发送和接收数据时统一使用字符串类型。
集线器中的方法。
public async Task SendList()
{
// Use JsonConvert.SerializeObject
await Clients.All.SendAsync("ReceiveMessage", "ForListData", JsonConvert.SerializeObject(new List<int>{ 1,2}));
}
在您的页面中。
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
if (type == "ForListData")
{
// Use JsonConvert.DeserializeObject
var list = JsonConvert.DeserializeObject<List<int>>(message);
//...
}
//...
string encodedMsg = $"{user}: {message}";
AllNotificationMessages.Add(new NotificationModel("Mon Titre"));
currentMessages = AllNotificationMessages.Where(elem => elem.Id != myMsg.Id).ToList();
StateHasChanged();
});