在 .NET 8 之前,在 Azure 函数中设置全局设置通常可以正常工作。现在,相同的代码在 .NET 8 和 Azure Functions v4 中不起作用:
// Setting global System.Text.Json.JsonSerializerOptions
services.Configure<JsonSerializerOptions>(options =>
{
options.PropertyNameCaseInsensitive = true;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault; // Property is ignored if its value is null. This is applied only to reference-type properties and fields.
});
不再支持此功能吗?我找不到任何有关如何在 .NET 8 中执行此操作的文档。
在 .NET 8 中,我需要将其注入到我的 Azure Functions 构造函数中才能工作。下面是将 JSON 序列化选项注入到我的主构造函数中的示例:
public class Function1(ILogger<Function1> logger, IOptions<JsonOptions> jsonOptions)
{
private readonly ILogger<Function1> _logger = logger;
private readonly JsonSerializerOptions _jsonOptions = jsonOptions.Value.SerializerOptions;
...
}
然后在反序列化方法中使用它作为参数:
var messageData = JsonSerializer.Deserialize<MyDTO>(message.Body, _jsonOptions);
这应用了我的设置,忽略 JSON 中字段名称的大小写。