.netcore2.1 统一接口返回属性名称

  为了开发规范,有时需要统一响应属性名称,.netcore已为我们封装好了,我们直接用即可。

  在StartUp类中ConfigureServices方法中,添加如下代码:

 public void ConfigureServices(IServiceCollection services)
        {
          
            services.AddMvc()
            .AddJsonOptions(opt =>
            {
                // opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();//原样输出,后台属性怎么写的,返回的 json 就是怎样的

               // opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();//驼峰命名法,首字母小写

                opt.SerializerSettings.ContractResolver =new LowercaseContractResolver();//自定义扩展,属性全为小写
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

  自定义全部小写扩展类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApi.Common.Extension
{
    public class LowercaseContractResolver: Newtonsoft.Json.Serialization.DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.ToLower();
        }
    }
}

 

你可能感兴趣的:(.netcore2.1 统一接口返回属性名称)