Refit调用.NET Core API时枚举JSON转换失败报400错误如何解决
解决方案
这个错误的核心原因是Refit端的JSON序列化规则与API端的JSON反序列化规则对枚举类型的处理不匹配,可通过以下任意一种方案统一两端的枚举处理逻辑解决:
方案1:配置API端支持枚举字符串反序列化(推荐,可读性更高)
修改API项目的Program.cs配置,给System.Text.Json添加枚举字符串转换器,同时开启大小写不敏感匹配:
builder.Services.AddControllers() .AddJsonOptions(options => { // 支持枚举字符串转枚举值 options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()); // 忽略属性名称大小写 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; });
如果你的API项目使用的是Newtonsoft.Json,替换为以下配置:
builder.Services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter()); });
方案2:配置Refit端序列化枚举为数字值
如果你希望保持API端默认仅接收数字枚举值的规则,修改Refit客户端注册配置,指定序列化时直接输出枚举的数字值:
// 在 Razor Pages 项目的Program.cs中注册Refit客户端时配置序列化规则 builder.Services.AddRefitClient<IPaymentAPI>(new Refit.RefitSettings { ContentSerializer = new Refit.SystemTextJsonContentSerializer( new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase, // 此处不要添加JsonStringEnumConverter,默认就会序列化枚举为数字 }) }) .ConfigureHttpClient(client => { client.BaseAddress = new Uri("你的API服务地址"); });
方案3:给指定枚举属性单独加序列化规则
如果不想修改全局配置,可以直接在共享的RechargeRequest模型的枚举属性上加特性,单独指定序列化规则:
public class RechargeRequest { // 加此特性指定枚举按字符串序列化/反序列化 [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] // 如果有大小写匹配问题可以加此特性指定序列化后的属性名 [System.Text.Json.Serialization.JsonPropertyName("licenseType")] public ELicenseType LicenseType{ get; set; } }
注意:请确保两端使用的JSON序列化组件一致,不要出现Refit用System.Text.Json、API端用Newtonsoft.Json的情况,两类组件的配置特性不互通。
内容的提问来源于stack exchange,提问作者Kishan Vaishnav
相关产品推荐
相关产品推荐

