Search code examples
json.net-corejson.netsignalr

Creating Windows Forms .Net Core app with SignalR


I've created a Windows Forms .Net Core app with SignalR .Net client. I followd this article https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-5.0&tabs=visual-studio to add packages and connect to the server. Everything works correctly when the server does not use NewtonsoftJson for serialization\deserialization. Once I enable NewtonsoftJson serialization\deserialization (serialization\deserialization works 100% correctly on the server which I can test using a client written on JavaScript), properties on the server with JsonProperty like the following

[JsonProperty(PropertyName = "EDT")]
public List<UpdateEDT> EDTs { get; set; }

always set null because, as I suspect, the SignalR Core client library does not serialise classes with NewtonsoftJson. I tried to install Microsoft.AspNetCore.Mvc.NewtonsoftJson and Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson nuget packages and tried to add AddNewtonsoftJsonProtocol() as the following

connection = new HubConnectionBuilder()
                .WithUrl("https://xxxxx/chat?access_token=" + token)
                .AddNewtonsoftJsonProtocol()
                .WithAutomaticReconnect()
                .Build();            

but AddNewtonsoftJsonProtocol() cannot be found. My question is how to configure SignalR .Net Core client library to use Newtonsoft for serialization and deserialization? Thanks.


Solution

  • It is turned out that I was doing everything correctly, but missed one using statement:

    using Microsoft.Extensions.DependencyInjection;