In .Net 6, when trying to use SignalR with JsonProtocol (System.Text.Json), my client program throws the following exception
System.IO.InvalidDataException: Error reading JSON.
---> System.Text.Json.JsonException: '{' is invalid after a value. Expected either ',', '}', or ']'. Path: $ | LineNumber: 0 | BytePositionInLine: 4090
Code on server side:
services.AddSignalR()
.AddJsonProtocol();
Code on client side:
conn = new HubConnectionBuilder()
.WithUrl($"{_serverBaseAddress}mainHub", o =>
{
o.AccessTokenProvider = InitializeOrRefreshAccessTokenIfNeeded;
o.Transports = HttpTransportType.WebSockets;
}
)
.ConfigureLogging(logging =>
{
logging.AddConsole();
})
.AddJsonProtocol()
.Build()
Note: everything works fine when using NewtonsoftJsonProtocol:
Code on server:
services.AddSignalR()
.AddNewtonsoftJsonProtocol(opts =>
{
opts.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.All;
});
Code on client:
conn = new HubConnectionBuilder()
.WithUrl($"{_serverBaseAddress}mainHub", o =>
{
o.AccessTokenProvider = InitializeOrRefreshAccessTokenIfNeeded;
o.Transports = HttpTransportType.WebSockets;
}
)
.ConfigureLogging(logging =>
{
logging.AddConsole();
})
.AddNewtonsoftJsonProtocol(
opts =>
opts.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.All
)
.Build();
There is a difference, with NewtonsoftJson I specify TypeNameHandling.All but I do not know any equivalent for System.Text.Json.
Why not just keep Newtonsoft.Json? I would like to use source generators and specify a SerializerContext like below:
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.AddContext<MyJsonSerializerContext>();
});
which I believe I cannot do with NewtonsoftJson