要让 ASP.NET Core .NET 6 应用默认返回 JSON 格式,可以按照如下步骤进行配置:
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
[HttpGet]
[Produces("application/json")] // 加上该特性确保返回 JSON 格式
public IActionResult Get()
{
var result = new { Name = "Jack", Age = 18 };
return Ok(result);
}
经过以上步骤配置后,ASP.NET Core .NET 6 应用将默认以 JSON 格式返回数据。