gpt4 book ai didi

c# - SignalR C# 客户端 Hubconnection.On 未触发

转载 作者:行者123 更新时间:2023-12-04 12:37:36 25 4
gpt4 key购买 nike

我有一个带有 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"
}
]
]
}

最佳答案

我终于找到了问题所在。它是关于序列化接收到的 json 消息。我不得不添加 .AddJsonProtocol() ,并进行设置,这里是最终代码:

_hubConnection = new HubConnectionBuilder()
.WithUrl("http://localhost:59225/hubs/accounthub", cfg =>
{
cfg.SkipNegotiation = true;
cfg.Transports = HttpTransportType.WebSockets;
cfg.AccessTokenProvider = () => Task.FromResult(token);
})
.AddJsonProtocol(cfg =>
{
var jsonOptions = new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
jsonOptions.Converters.Add(new JsonStringEnumConverter());

cfg.PayloadSerializerOptions = jsonOptions;
})
.Build();
我觉得奇怪的是我没有收到任何错误消息顺便说一句。

关于c# - SignalR C# 客户端 Hubconnection.On 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62872178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com