ABP .Net Core To Json序列化配置

 1、 前言前端

咱們採用ABP架構用MVC Controller或Web API返回給前端結果ToJson序列化後獲得的屬性命名都是採用js的駝峯格式,即首字母小寫,後面單詞首字母大寫的格式(如:後臺屬性名爲OrderName,返回的前端js爲orderName)。但在實際項目開發中因爲某種緣由(好比給老系統提供接口或現有系統集成等)須要採用給後臺屬性名一致或本身特定的格式,下面就介紹一下基於ABP架構ToJson如何修改默認配置和自定義配置。json

2、 修改ToJson序列化默認配置架構

在Startup文件進行默認配置修改,代碼以下:app

public class Startup
{
        private readonly IConfigurationRoot _appConfiguration;
public Startup(IHostingEnvironment env) { _appConfiguration = env.GetAppConfiguration(); } public IServiceProvider ConfigureServices(IServiceCollection services) { // MVC services.AddMvc()
       .AddJsonOptions(options
=> { //配置tojson格式配置 DefaultContractResolver 爲和後臺屬性名保持一致(即:後臺屬性名爲OrderName,前端js得到屬性名也爲OrderName options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //修改成CamelCasePropertyNamesContractResolver,爲js的駝峯格式,即abp默認格式(即:後臺屬性名爲OrderName,前端js得到屬性名爲orderName //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); });      } }

 

3、ToJson序列化自定義配置ide

若是須要自定義ToJson序列化格式,須要先寫一個子類繼承DefaultContractResolver,重寫ResolvePropertyName方法,代碼以下:spa

public class MyPropertyNamesContractResolver : DefaultContractResolver
{
        protected override string ResolvePropertyName(string propertyName)
        {
            //屬性名所有返回小寫
            return propertyName .ToLower();
        }
}

再參考第二點在Startup文件將配置替換爲MyPropertyNamesContractResolvercode

services.AddMvc()
.AddJsonOptions(options
=> { //配置tojson格式替換爲自定義格式 MyPropertyNamesContractResolver (即:後臺屬性名爲OrderName,前端js得到屬性名爲ordername options.SerializerSettings.ContractResolver = new MyPropertyNamesContractResolver(); });
相關文章
相關標籤/搜索