【发布时间】:2020-09-29 16:56:09
【问题描述】:
我想设置一个全局设置,在从我的任何 HTTP 函数返回的任何响应中不返回 null 属性。
例子:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
[FunctionName("HttpTriggeredFunction")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
var user = new User
{
Id = 1,
FirstName = "Chris",
LastName = null
};
return new OkObjectResult(user);
}
返回:
{
"id": 1,
"firstName": "Chris",
"lastName": null
}
在上面的示例中,我希望lastName 不在响应中返回。
我知道您可以执行以下操作:
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
但我不想装饰每个班级。
在 Web API 中,在 Startup.cs 文件中,您可以执行以下操作:
services.AddMvcCore().AddNewtonsoftJson(jsonOptions =>
{
jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
【问题讨论】:
-
@J.Bergmann 这看起来像我需要的,但我在运行时收到此错误
Could not load type 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' from assembly 'Microsoft.AspNetCore.Mvc.Formatters.Json, Version=3.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
标签: c# azure json.net azure-functions