為了開發規範,有時需要統一響應屬性名稱,.netcore已為我們封裝好了,我們直接用即可。 在StartUp類中ConfigureServices方法中,添加如下代碼: public void ConfigureServices(IServiceCollection services) { serv ...
為了開發規範,有時需要統一響應屬性名稱,.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(); } } }