当前位置: 首页 > news >正文

ASP.NET Core 3.1 修改个别API返回JSON序列化格式

        ASP.NET Core 3.0及之后的版本中,默认的JSON格式化器是基于System.Text.Json的。返回json格式采用camelCase(第一个单词首字母小写,后面单词首字母大写)。如果想改为PascalCase,可以全局设置PropertyNamingPolicy = null即可。

services.AddControllers()
.AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

或者 使用NewtonsoftJson,并指定序列化设置。

 services.AddControllers()
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

        如果想改变个别接口为PascalCase格式,有以下几种方式
1、增加NewtonsoftJson支持,并配置返回模型属性JsonProperty,指定序列化后属性名。   不推荐,太麻烦。

services.AddControllers().AddNewtonsoftJson();

//action返回的模型
 public class Model
{
    [JsonProperty("Information")]
    public string Information { get; set; }
}

2、利用ActionFilterAttribute改变行为。

public class CustomActionJsonFormatAttribute : ActionFilterAttribute
{
    private Type _ContractResolver { get; set; }
    public CustomActionJsonFormatAttribute(Type ContractResolver)
    {
        _ContractResolver = ContractResolver;
    }
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is ObjectResult objectResult)
        { 

            //2.1 设定OutputFormatter   推荐
            objectResult.Formatters.Add(new SystemTextJsonOutputFormatter(new JsonSerializerOptions() { }));


        //2.2  这种方式也可以,相当于手工转换了一遍。不推荐
        //var properties = context.Result.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
        //var t = properties.FirstOrDefault(c => c.Name == "Value").GetValue(context.Result);
        //context.Result = new JsonResult(t, new System.Text.Json.JsonSerializerOptions());  


           //2.3 残暴一点,将结果序列化之后以字符串方式输出也能实现。但是极不推荐,这种返回的不再是json,而是字符串。
           // var settings = new JsonSerializerSettings
           // {
           //     DateFormatString = "yyyy-MM-dd HH:mm:ss", // 自定义日期格式
            //    ContractResolver = new DefaultContractResolver() // 使用默认的契约解析器
            //};

            //var json = JsonConvert.SerializeObject(objectResult.Value, settings);       
            //context.HttpContext.Response.WriteAsync(json);
             
        }

        base.OnResultExecuting(context);
    } 
}


//controller中加上对应特性
   [CustomActionJsonFormat(typeof(DefaultContractResolver))]
    public class FarmerFileController : ControllerBase


3 、采用自定义的MediaType。默认返回json格式,我们自定义一个格式,本质还是json字符串,只不过采用PascalCase。因为http返回的已经不是json格式,不推荐。

//action中增加Produces特性,配置自定义的content type,接口返回的Result可以随便定义一个模型。
[Produces("text/object")]。
[HttpGet("Query2")]
public async  Task<Result> Query2(DateTime? dataDate, bool hasPig = false)
{}


//自定义OutputFormatter
    public class ObjectOutputFormatter : TextOutputFormatter
    {
        public ObjectOutputFormatter()
        {
            SupportedEncodings.Add(Encoding.UTF8);
            SupportedEncodings.Add(Encoding.Unicode);
            // 这样 content type 为 "text/object"时,就被会ObjectOutputFormatter 处理
            SupportedMediaTypes.Add("text/object"); 
        }

        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (selectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(selectedEncoding));
            }
            
            string text = JsonConvert.SerializeObject(context.Object);
            var response = context.HttpContext.Response;
            await response.WriteAsync(text, selectedEncoding);
        }
    }

//注入 services
services.AddControllers(options =>
 {
     options.OutputFormatters.Add(new ObjectOutputFormatter());
 })


4、修改action返回结果,直接返回自定义序列化配置的JsonResult。这种方式要求修改action返回结果,不太推荐

public async Task< IActionResult> Query3(DateTime? dataDate, bool hasPig = false)
{
    var result = new Result()
    {         
    }; 

    return new JsonResult(result, new Newtonsoft.Json.JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
    });
}



//增加NewtonsoftJson支持
  services.AddControllers().AddNewtonsoftJson() ;

参考文章
https://www.cnblogs.com/cool-net/p/16176643.html
https://www.cnblogs.com/wucy/p/18025196/aspnetcore_webapi_formatter 
https://www.cnblogs.com/qianxingmu/p/13963720.html

相关文章:

  • MySQL整体架构
  • Docker - 网络
  • 用冒泡排序法模拟qsort函数
  • LabVIEW中三种PSD分析VI的区别与应用
  • 微调训练方法概述:Fine-tuning、Prompt-tuning、P-tuning 及其他高效技术
  • pwa的基本使用
  • 2W8000字 LLM架构文章阅读指北
  • pytorch2.6.0版本测试YOLOv5中detect.py错误解决办法
  • http报文的content-type参数和spring mvc传参问题
  • 高频 SQL 50 题(基础版)_550. 游戏玩法分析 IV
  • 系统架构设计师—计算机基础篇—系统性能评价
  • 深度学习pytorch之4种归一化方法(Normalization)原理公式解析和参数使用
  • 小结:BGP协议
  • AtCoder Beginner Contest 001(A - 積雪深差、B - 視程の通報、C - 風力観測、D - 感雨時刻の整理)题目翻译
  • 贪心算法+题目
  • Sqli-labs
  • 从零开始用react + tailwindcss + express + mongodb实现一个聊天程序(八) 聊天框用户列表
  • ByteBuddy
  • 联合省选 2025 游记
  • 【随手笔记】FFT+音乐频谱(二)
  • 电脑做网站怎么解析域名/吸引客人的产品宣传句子
  • 抖音运营/seo教程之关键词是什么
  • 物流公司网站怎么做/新东方在线教育平台官网
  • 提供东莞网站制作公司/怎样才能在百度上发布信息
  • 百度优化服务/北京seo优化多少钱
  • 地产网站建设方案/什么网站百度收录快