带有 SignalR 发送对象的 Blazor WASM

Blazor WASM with SignalR sending objects

我有一个 class 我正在尝试从带有 signalR 的 WebAPI 服务器发送到 Blazor WASM。我使用了新的 Blazor 模板,并选中了 .net 核心托管选项。它可以很好地向 NewUser 方法发送字符串或整数,但是当使用像下面看到的 User 这样的自定义对象时,我什么也得不到。我认为有问题 serializing/deserializing 但我找不到任何选项。我在配置中遗漏了什么吗?

public class User
{
    public string Id { get; set; }

    [Required(ErrorMessage ="You must specify a username")]
    [StringLength(20,MinimumLength=1,ErrorMessage="Please enter a username no longer than 20 characters")]
    public string Username { get; set; }
    public string ConnectionId { get; set; }
}

中心

    public async Task Register(AppState state)
    {
        await _roomRepository.RegisterUser(state);
        await Groups.AddToGroupAsync(state.user.ConnectionId,state.matchroom.Id);
        await Clients.Group(state.matchroom.Id).SendAsync("NewUser", $"{state.user}");
    }

Startup.cs(WebAPI 服务器)省略了很多

services.AddSignalR();
services.AddResponseCompression(opts =>
      {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });

Blazor 页面

protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(NavigationManager.ToAbsoluteUri("/matchhub"))
            .Build();

        hubConnection.On<User>("NewUser", (user) =>
        {
            AppState.matchroom.Users.Add(user);
            StateHasChanged();
        });
    await hubConnection.StartAsync();
    AppState.user.ConnectionId = hubConnection.ConnectionId;
    await hubConnection.SendAsync("register", AppState)
    }

看起来您正在将 state.user 作为字符串写入并发送,因此客户端无法将 User 类型与其接收到的 string 类型相匹配。