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

为何Refit序列化URL参数布尔值时首字母大写?

解决Refit序列化GET请求URL布尔参数为大写的问题

问题背景

在ASP.NET 6的Refit接口中,GET请求的URL参数里布尔值会被序列化为大写的True/False,导致目标API返回400错误。而POST请求体中的布尔值则正常显示为小写,尝试修改JSON序列化配置、自定义JsonConverter都无效——因为Refit处理URL参数和请求体用的是完全不同的机制。

核心原因

Refit默认使用System.ComponentModel.TypeConverter处理URL查询参数的序列化,而非JSON序列化器。这就是为什么你调整JSON相关配置完全不起作用的根本原因。

有效解决方案

方案1:自定义布尔类型的TypeConverter

创建一个将布尔值转为小写字符串的TypeConverter,然后标记在对应的属性上:

public class LowercaseBooleanTypeConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string) && value is bool boolValue)
        {
            return boolValue ? "true" : "false";
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

修改请求对象的属性:

[TypeConverter(typeof(LowercaseBooleanTypeConverter))]
public bool include_totals { get; set; }

方案2:配置Refit使用JSON序列化处理查询参数

Refit 6.0及以上版本支持配置QueryUriFormat为JsonSerializer,让URL参数使用JSON序列化规则(包括小写布尔):

services.AddRefitClient<IAuth0ManagementApi>(new RefitSettings
{
    QueryUriFormat = QueryUriFormat.JsonSerializer
})
.ConfigureHttpClient(client =>
{
    client.BaseAddress = new Uri("你的API基础地址");
});

方案3:临时手动处理(适合快速验证)

如果不想修改全局配置或写转换器,可以将请求对象的布尔属性改为字符串类型,在getter中手动转换:

private bool _includeTotals;
public string include_totals
{
    get => _includeTotals ? "true" : "false";
    set => _includeTotals = bool.Parse(value);
}

或者直接在接口中单独传递布尔参数(避免使用对象):

[Get("/users")]
Task<Auth0GetUsersResponse> GetUsers([Query] bool include_totals, [Header("Authorization")] string bearerToken);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:45:32