0
点赞
收藏
分享

微信扫一扫

2019-9-23-asp-dotnet-core-3.0-接口返回-json-使用-PascalCase-格式

Hyggelook 2024-10-30 阅读 10

title

author

date

CreateTime

categories

asp dotnet core 3.0 接口返回 json 使用 PascalCase 格式

lindexi

2019-09-23 18:39:17 +0800

2019-09-21 11:53:45 +0800

dotnet

在 asp dotnet core 3.0 默认的 webapi 返回接口都是返回 json 格式,同时这个 json 格式使用的是 CamelCase 属性名风格。如果想要兼容之前的格式,让 webapi 返回的 json 的属性名使用 PascalCase 格式,那么请看本文

默认的 ASP.NET Core 3.0 的 WebAPI 的 json 返回值的属性使用首字符小写的 CamelCase 属性名风格,可以通过在 ConfigureServices 方法配置让返回值属性使用其他风格

最简单的方法是设置 PropertyNamingPolicy 属性,请看代码

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

另一个是通过 NewtonsoftJson 设置

首先安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 库

安装之后可以在 Startup.cs 文件里面的 ConfigureServices 方法添加设置

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new DefaultNamingStrategy() });
        }

这样默认的 json 返回值属性使用首字符大写的 PascalCase 属性名风格

使用 DefaultContractResolver 就是 PascalCase 风格

使用 CamelCasePropertyNamesContractResolver 就是 CamelCase 风格

注意,在一些版本,可以是 AddMvc 方法,请看下面

services.AddMvc()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new DefaultContractResolver());

Migrate from ASP.NET Core 2.2 to 3.0 Preview

Serializing a PascalCase Newtonsoft.Json JObject to camelCase










举报

相关推荐

0 条评论