如何为 Azure SignalR 管理库配置底层 JSON 序列化选项?

问题描述 投票:0回答:2

我试图弄清楚如何配置 Azure SignalR 管理库使用的 JSON 序列化设置。如何指定 JSON 应使用驼峰式属性名称而不是大写名称进行序列化?

这里有一些发送消息的代码...

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();
    }
}

您可以看到我提供了一个

LogMessage
实例作为消息参数。
SendCoreAsync
方法使用大写属性名称对其进行序列化。我希望将其配置为使用驼峰命名法属性发送。

这是使用

Microsoft.Azure.SignalR.Management
nuget 包。

signalr-hub azure-signalr
2个回答
2
投票

看来你可以:-)我花了很多时间才找到这个,并且在最终找到这个解决方案之前我遇到了很多建议的解决方案(但不起作用)。

如果您使用 System.Text.Json 序列化程序,请在启动类的配置方法中使用它。

builder.Services.Configure<SignalROptions>(o => o.JsonObjectSerializer = new JsonObjectSerializer(
new JsonSerializerOptions()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
}));

如果您使用 Newtonsoft,请改用它

builder.Services.Configure<SignalROptions>(o => o.JsonObjectSerializer = new NewtonsoftJsonObjectSerializer(
new JsonSerializerSettings()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
}));

这是我从GitHub

得到解决方案的文章

0
投票

响应提供了问题所在的提示,但在示例代码中,他使用的是 CreateServiceManager 和 CreateHubContextAsync,我也在使用它们,并且我的启动类中没有构建器,因为这不在 Azure 函数中。我希望我的 C# .Net Core API 在无服务器模式下使用 Azure SignalR,这就是让它为我工作的原因。添加如下 .WIthOptions 部分,更新消息发布者/发送者以驼峰式大小写进行序列化,默认情况下并非如此:

            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);
© www.soinside.com 2019 - 2024. All rights reserved.