首页 新闻 会员 周边

如何设置NET6 WebApi JSON传到前台默认变成小驼峰

0
悬赏园豆:5 [已解决问题] 解决于 2023-04-07 21:07

.NET6 WebAPI默认出传到前台自动转化成小驼峰写法,如何设置某个controller返回值为大驼峰(我问的时单个设置某个controller返回值为大驼峰,不是全局都设置为大驼峰)

天亦玄的主页 天亦玄 | 初学一级 | 园豆:32
提问于:2023-01-17 23:34
< >
分享
最佳答案
2
收获园豆:2
czd890 | 专家六级 |园豆:14412 | 2023-01-18 01:02

好文!学习了

  • 添加 named json settings
builder.Services.AddControllers().AddJsonOptions("old", options => {});
  • 添加 endpoint metadata
public class JsonSettingsNameAttribute : Attribute { }

[JsonSettingsName("old")]
public class OldApiController : ControllerBase {}
}
  • 读取 endpoint metadata
public static string? GetJsonSettingsName(this HttpContext context)
{
    return context.GetEndpoint()
        ?.Metadata
        .GetMetadata<JsonSettingsNameAttribute>()
        ?.Name;
}
  • 实现 SpecificSystemTextJsonInputFormatter 重写 CanRead
public override bool CanRead(InputFormatterContext context)
{
    if (context.HttpContext.GetJsonSettingsName() != SettingsName)
        return false;

    return base.CanRead(context);
}
  • 实现 SpecificSystemTextJsonOutputFormatter 重写 CanWriteResult
public override bool CanWriteResult(OutputFormatterCanWriteContext context)
{
    if (context.HttpContext.GetJsonSettingsName() != SettingsName)
        return false;
        
    return base.CanWriteResult(context);
}
  • 实现 ConfigureMvcJsonOptions
public class ConfigureMvcJsonOptions : IConfigureOptions<MvcOptions> {}
  • 注册 ConfigureMvcJsonOptions
builder.Services.AddSingleton<IConfigureOptions<MvcOptions>>(sp =>
{
    var options = sp.GetRequiredService<IOptionsMonitor<JsonOptions>>();
    var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
    return new ConfigureMvcJsonOptions(settingsName, options, loggerFactory);
});
dudu | 园豆:30994 (高人七级) | 2023-01-18 10:47
其他回答(1)
0


options.JsonSerializerOptions.PropertyNamingPolicy = null;//区分大小写

收获园豆:3
Giant150 | 园豆:1165 (小虾三级) | 2023-01-18 14:07
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册