我如何配置 ASP.NET Core Web Api 控制器Development
只为环境返回格式化的 json?
默认情况下,它返回如下内容:
{"id":1,"code":"4315"}
为了可读性,我想在响应中缩进:
{
"id": 1,
"code": "4315"
}
我如何配置 ASP.NET Core Web Api 控制器Development
只为环境返回格式化的 json?
默认情况下,它返回如下内容:
{"id":1,"code":"4315"}
为了可读性,我想在响应中缩进:
{
"id": 1,
"code": "4315"
}
.NET Core 2.2 及更低版本:
在您的Startup.cs
文件中,调用AddJsonOptions
扩展名:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
});
请注意,此解决方案需要Newtonsoft.Json
.
.NET Core 3.0 及更高版本:
在您的Startup.cs
文件中,调用AddJsonOptions
扩展名:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
至于根据环境切换选项,这个答案应该会有所帮助。
如果您想为单个控制器而不是所有 JSON 打开此选项,您可以让您的控制器返回一个 JsonResult 并在构造 JsonResult 时传递 Formatting.Indented ,如下所示:
return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented } };
在 .NetCore 3+ 中,您可以按如下方式实现:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.WriteIndented = true;
});
在我的项目中,我Microsoft.AspNetCore.Mvc
将以下代码用于所有控制器。这适用于 .NET Core 3。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
});
}
如果您只希望此选项用于特定操作,请使用 System.Text.Json
return new JsonResult(myResponseObject) { SerializerSettings = new JsonSerializerOptions() { WriteIndented = true } };