如何配置Azure SignalR Management库的JSON序列化选项实现驼峰输出
配置方案
前提依赖
根据你使用的序列化组件安装对应扩展包:
- 若使用Newtonsoft.Json作为序列化组件,安装NuGet包:
Microsoft.Azure.SignalR.Management.NewtonsoftJson - 若使用System.Text.Json作为序列化组件,无需额外安装基础包,直接配置即可
注:以下配置方案适用于
Microsoft.Azure.SignalR.Management1.10.0及以上稳定版本,旧版本兼容方案见末尾说明。
配置代码示例
修改你的CreateServiceManager方法,添加序列化配置即可,不需要调整现有消息发送逻辑:
使用Newtonsoft.Json配置小驼峰
using Microsoft.Azure.SignalR.Management; using Newtonsoft.Json.Serialization; private static IServiceManager CreateServiceManager(string connectionString) { var builder = new ServiceManagerBuilder() .WithOptions(options => { options.ConnectionString = connectionString; }) // 添加NewtonsoftJson序列化配置 .AddNewtonsoftJson(serializerOptions => { serializerOptions.PayloadSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); return builder.Build(); }
使用System.Text.Json配置小驼峰
using Microsoft.Azure.SignalR.Management; using System.Text.Json; private static IServiceManager CreateServiceManager(string connectionString) { var builder = new ServiceManagerBuilder() .WithOptions(options => { options.ConnectionString = connectionString; }) // 添加System.Text.Json序列化配置 .AddSystemTextJson(serializerOptions => { serializerOptions.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }); return builder.Build(); }
注意事项
配置完成后所有发送的自定义对象都会自动按小驼峰规则序列化属性名,如果你的LogMessage类中手动指定了JsonPropertyName(System.Text.Json)或JsonProperty(Newtonsoft.Json)特性的属性名,会优先使用特性中指定的名称。
低于1.10.0版本兼容方案
如果使用的是旧版本包,需要手动实现序列化逻辑,在调用SendCoreAsync之前先将对象序列化为小驼峰格式的JSON字符串再传递,或者自定义IHubProtocol注入到服务容器中,推荐优先升级到最新稳定版使用上述更简便的配置方案。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

