You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Flurl 4.0全局或指定客户端配置Newtonsoft JSON序列化

Flurl 4.0 配置Newtonsoft JSON序列化(全局/指定客户端)

首先需要安装Flurl的Newtonsoft JSON扩展包,因为Flurl 4.0默认使用System.Text.Json作为序列化器:

# NuGet包管理器命令
Install-Package Flurl.NewtonsoftJson

# 或.NET CLI命令
dotnet add package Flurl.NewtonsoftJson

(a) 全局配置(所有请求默认使用Newtonsoft JSON)

在应用启动阶段(比如Program.cs、Startup.cs的初始化逻辑中),通过FlurlHttp.Configure设置全局默认序列化器:

FlurlHttp.Configure(settings => {
    // 初始化Newtonsoft序列化器,可自定义JsonSerializerSettings
    settings.JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings {
        DateFormatString = "yyyy-MM-dd HH:mm:ss",
        NullValueHandling = NullValueHandling.Ignore,
        // 可添加更多自定义配置,比如驼峰命名、引用循环处理等
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    });
});

配置完成后,所有通过Flurl发起的请求(包括直接使用Url.xxx()扩展方法、未单独配置的FlurlClient实例)都会自动使用Newtonsoft JSON进行序列化/反序列化。

(b) 为指定客户端的所有请求配置

修改你提供的Create辅助方法,在创建FlurlClient实例时指定序列化器即可,无需全局配置:

using Flurl.Http.Newtonsoft;
using Newtonsoft.Json;

public static IFlurlClient Create
(
    string url,
    string? proxy = null
)
{
    // 定义Newtonsoft序列化配置,可根据需求调整
    var jsonSettings = new JsonSerializerSettings {
        DateFormatString = "yyyy-MM-dd HH:mm:ss",
        NullValueHandling = NullValueHandling.Ignore
    };
    var newtonsoftSerializer = new NewtonsoftJsonSerializer(jsonSettings);

    IFlurlClient client = string.IsNullOrEmpty(proxy)
        ? new FlurlClient(url) { Serializer = newtonsoftSerializer }
        : new FlurlClientBuilder(url)
            .ConfigureInnerHandler(h => {
                h.Proxy = new WebProxy(proxy);
                h.UseProxy = true;
            })
            // 通过Configure方法为客户端指定序列化器
            .Configure(client => client.Serializer = newtonsoftSerializer)
            .Build();

    return client;
}

通过这个方法创建的所有FlurlClient实例,其发起的所有请求都会使用Newtonsoft JSON序列化,不会影响其他未配置的客户端或全局设置。

内容的提问来源于stack exchange,提问作者Alek Davis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:45:07