You need to enable JavaScript to run this app. 如何为Azure Function SignalR Service Binding自定义JSON序列化配置?
优惠活动
大模型
产品
解决方案
定价
更多

如何为Azure Function SignalR Service Binding自定义JSON序列化配置?

Azure Function SignalR Service输出绑定枚举序列化为字符串解决方案

全局配置方案

SignalR Service输出绑定扩展支持直接读取依赖注入容器中的序列化配置,无需手动修改扩展内部逻辑,两种序列化器的配置方式如下:

使用System.Text.Json(适用于v1.8.0+版本的SignalR扩展)

在进程内(In-Process)模式的Function启动类中注入序列化配置即可:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
using System.Text.Json.Serialization;

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.Configure<JsonSerializerOptions>(options =>
            {
                // 全局添加枚举转字符串转换器
                options.Converters.Add(new JsonStringEnumConverter());
            });
        }
    }
}

使用Newtonsoft.Json

同样在启动类中配置Newtonsoft的序列化设置:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.Configure<JsonSerializerSettings>(settings =>
            {
                // 全局添加枚举转字符串转换器
                settings.Converters.Add(new StringEnumConverter());
            });
        }
    }
}

独立工作进程(Isolated Worker)模式配置

如果使用Isolated模式运行Function,直接在Program.cs中添加配置即可:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        // System.Text.Json配置
        services.Configure<JsonSerializerOptions>(options =>
        {
            options.Converters.Add(new JsonStringEnumConverter());
        });
        // 若使用Newtonsoft则替换为对应配置即可
    })
    .Build();

host.Run();

说明:如需指定SignalR扩展优先使用的序列化器,可在应用配置中添加SignalR__Serializer设置,取值为SystemTextJson或NewtonsoftJson,默认使用Newtonsoft.Json。

单枚举生效方案

如果不需要全局所有枚举都序列化为字符串,仅需要特定枚举生效,可以直接在枚举定义上添加转换器特性,无需全局配置:

  • 适配System.Text.Json:
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum MyBusinessEnum
{
    OptionA,
    OptionB
}
  • 适配Newtonsoft.Json:
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public enum MyBusinessEnum
{
    OptionA,
    OptionB
}

注意:不要自行将业务对象序列化为JSON字符串后传入SignalR输出绑定,库会将字符串识别为普通值进行二次序列化,导致出现多余的转义字符,直接传入原始对象即可,上述配置会自动在序列化阶段生效,不会出现转义异常问题。

内容的提问来源于stack exchange,提问作者Ilya Chernomordik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:27:05