Search code examples
javascriptc#asp.net-coresignalrasp.net-core-signalr

asp.net core 3.1 SignalR: pass complex object from javascript client to Hub


I'm trying to pass an object from client to hub: On client:

connection.invoke('MyMethod', {
                i: 1,
                a: 25
            });

On hub:

        public async Task MyMethod(TestModel model)
        {
            // logic
        }

Model:

public class TestModel
{
    [JsonProperty("i")]
    public double Min {get;set;}
    [JsonProperty("a")]
    public double Max {get;set;}
}

In the MyMethod the model is not null, but the values are always 0.

What I'm doing wrong?


Solution

  • According to your description, you should use Newtonsoft.Json in an ASP.NET Core 3.0 SignalR project, since the asp.net core doesn't use Newtonsoft.Json by default.

    You should install the Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson NuGet package and then modify the startp.cs ConfigureServices method as below:

    services.AddSignalR()
        .AddNewtonsoftJsonProtocol();
    

    More details, you could refer to this article.