我有一个带有 signalR 的 ASPNet.Core WebApi。我有使用 webAPI 的 angular 应用程序,我想用 Blazor Webassembly 应用程序替换它。我在 Blazor 应用程序中遇到 signalR 问题。
我创建了一个 hubconnection,设置它,当服务器发送数据时,Hubconnection.On 方法没有被调用。这是我的代码:
protected override async Task OnInitializedAsync()
{
_hubConnection = new HubConnectionBuilder()
.WithUrl("https://localhost:45299/hubs/accounthub", cfg =>
{
cfg.SkipNegotiation = true;
cfg.AccessTokenProvider = () => Task.FromResult(token);
cfg.Transports = HttpTransportType.WebSockets;
})
.Build();
_hubConnection.On<IEnumerable<AccountResponse>>("accountschanged", (accounts) =>
{
foreach(var account in accounts)
{
Console.WriteLine(account.Name);
}
});
await _hubConnection.StartAsync();
}
在网络选项卡中,我看到连接正常,我收到了新数据,但是 hubconnection.On 中的方法没有被触发。我仔细检查了方法名称,它是相同的。在 Angular 应用程序中,它工作正常,并且随着数据从服务器发送,服务器代码没有任何问题。
我使用 Fluxor 进行状态管理,并在 'On' 方法中触发了一个操作,为了简单起见,我只是用单个 Console.WriteLine 替换了它。
编辑:添加服务器代码,并收到消息这是服务器代码,更改帐户时会调用“AccountsChanged”:
public class AccountHub : Hub, IAccountHub
{
private readonly IHubContext<AccountHub> _accHub;
private readonly IAggregateMapper _mapper;
public AccountHub(IHubContext<AccountHub> accHub, IAggregateMapper mapper)
{
_accHub = accHub;
_mapper = mapper;
}
public async Task AccountsChanged(Guid userId, IEnumerable<Account> accounts)
{
var mapped = _mapper.MapAll<Account, AccountResponse>(accounts);
await _accHub.Clients.User(userId.ToString()).SendAsync("accountschanged", mapped);
}
}
这是我收到的消息(我从 Postman 发出请求),从网络选项卡复制(为了简单起见,我删除了帐户的其他属性):
{
"type":1,
"target":"accountschanged",
"arguments":[
[
{
"id":1,
"name":"bank account 1"
},
{
"id":2,
"name":"wallet 1"
}
]
]
}