I would like to set a global setting for not returning null
properties in any response returned from any of my HTTP functions.
Example:
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);
}
returns:
{
"id": 1,
"firstName": "Chris",
"lastName": null
}
In the above example, I want lastName
to not be returned in the response.
I'm aware you can do things like:
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
but I don't want to have to decorate every class.
In Web API, in the Startup.cs
file, you could do something like this:
services.AddMvcCore().AddNewtonsoftJson(jsonOptions =>
{
jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});