ASP.NET Core Json格式化響應數據

設置 ASP.NET Core Web API 中響應數據的格式
添加 XML 格式支持  
配置基於 System.Text.Json 的格式化程序  
添加基於 Newtonsoft.Json 的 JSON 格式支持  
ASP.NET Core 中的模型綁定  
*
1、注意在 ASP.NET Core 3.0 中 MVC 與 API 是不一樣的
基於 System.Text.Json 格式
MVC:services.AddMvc().AddJsonOptions(options => { options.SerializerOptions.PropertyNamingPolicy = null; });
API:services.AddControllers().AddJsonOptions(options => { options.SerializerOptions.PropertyNamingPolicy = null; });
基於 Newtonsoft.Json 格式
MVC:services.AddMvc().AddNewtonsoftJson(options => { options.SerializerOptions.PropertyNamingPolicy = null; });
API:services.AddControllers().AddNewtonsoftJson(options => { options.SerializerOptions.PropertyNamingPolicy = null; });

2、Startup.cs

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options =>
    {
        //忽略循環引用
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

*
*
*
*
2、
*
*

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章