Search code examples
signalr-hubazure-signalr

How to configure underlying JSON serialization options for Azure SignalR Management library?


I'm trying to figure out how to configure the JSON serialization settings that the Azure SignalR Management library uses. How can I specify that the JSON should be serialized with camelCase property names instead of UpperCase names?

Here's a bit of code that sends a message ...

private static IServiceManager CreateServiceManager(string connectionString)
{
    var builder = new ServiceManagerBuilder()
        .WithOptions(options => { options.ConnectionString = connectionString; });

    return builder.Build();
}

public static async Task SendLogMessageAsync(string connectionString, string userId, LogMessage logMessage)
{
    using (var manager = CreateServiceManager(connectionString))
    {
        var hubContext = await manager.CreateHubContextAsync("SystemEventHub");

        await hubContext.Clients.User(userId).SendCoreAsync("ReceiveLogMessage", new[] { logMessage });

        await hubContext.DisposeAsync();
    }
}

You can see that I'm providing a LogMessage instance as the message parameter. The SendCoreAsync method is serializing it using UpperCase property names. I'd like that to be configured to send using camelCase properties.

This is using the Microsoft.Azure.SignalR.Management nuget package.


Solution

  • The response provided a hint to what the problem, but in the example code he is using the CreateServiceManager and CreateHubContextAsync, which I am using too, and there's no builder in my startup classes because this isn't in an Azure Function. I'm wanting my C# .Net Core API to use the Azure SignalR in Serverless mode, and here's what got it to work for me. Adding the .WIthOptions section as below, updated the message publisher/sender to serialize in camel case, which it didn't by default:

                using var serviceManager = new ServiceManagerBuilder()
                .WithConfiguration(_configuration)
                .WithOptions(o => o.UseJsonObjectSerializer(new JsonObjectSerializer(
                    new JsonSerializerOptions()
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    })))
                .WithLoggerFactory(_loggerFactory)
                .BuildServiceManager();
    
            _hubContext = await serviceManager.CreateHubContextAsync(_hubName, cancellationToken);