I'm returning an object from my Azure function using OkObjectResult
, but the object's JSON still contains properties I've marked JsonIgnore
. Why is that, and how can I fix it?
Details:
I have this class:
using System.Text.Json.Serialization;
// ...
public class Example
{
public string A { get; set; }
public string B { get; set; }
[JsonIgnore]
public string C { get; set; }
}
When returning from an Azure function, if I do:
var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(result);
...the JSON returned is (I've added formatting):
{
a: "Ayy",
b: "Bee",
c: "See"
}
Notice that the JsonIgnore
attribute didn't take effect, the JSON has a c
property.
But if I serialize explicitly:
var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(
JsonSerializer.Serialize(
result,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase}
)
);
...c
is left out as desired:
{
a: "Ayy",
b: "Bee"
}
Why isn't the property being left out when I give the object to OkObjectResult
directly, and how do I fix it?