You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Cosmos DB触发器时避免含日期序列化字符串的时区转换

问题:Azure Functions隔离模型中Cosmos DB触发器自动转换DateTime时区的问题

我们正在将Cosmos DB触发的Azure函数从进程内模型迁移至隔离模型,为保留流畅JSON Schema能力,未使用POCO类作为触发器输入,而是采用JObject。

触发器代码如下:

[CosmosDBTrigger(
    databaseName: "%SourceCosmosDatabaseName%",
    containerName: OurContainerName,
    Connection = "CosmosConnectionString",
    LeaseDatabaseName = "%CosmosDatabaseName%",
    LeaseContainerName = LeaseContainerName,
    LeaseContainerPrefix = LeaseContainerNewStatusPrefix,
    CreateLeaseContainerIfNotExists = true,
    StartFromBeginning = true)]
IReadOnlyList<JObject> inputs,
FunctionContext functionContext

遇到的问题是:Azure函数会自动解析含日期时间的字符串并转换为DateTime类型,且转换为服务器时区,例如字符串"2023-05-15T20:05:00-05:00"会变为"2023-05-16T04:05:00+03:00"。

曾尝试通过全局Worker序列化设置添加DateParseHandling.None选项,但未生效,代码如下:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults(builder =>
    {
        builder.Services.Configure<WorkerOptions>(options =>
        {
            var settings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings();
            settings.DateParseHandling = DateParseHandling.None;
            options.Serializer = new NewtonsoftJsonObjectSerializer(settings);
        });
    })

解决方案

全局WorkerOptions的序列化设置仅作用于函数的通用输入输出绑定(如HTTP请求/响应),而Cosmos DB触发器的序列化由Cosmos DB SDK独立处理,需单独配置Cosmos的序列化器:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        // 配置Cosmos DB使用自定义Newtonsoft序列化器,禁用日期自动解析
        services.AddSingleton<ICosmosDBSerializer>(_ =>
        {
            var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings
            {
                DateParseHandling = Newtonsoft.Json.DateParseHandling.None
            };
            return new CosmosDBNewtonsoftSerializer(jsonSettings);
        });
    })
    .Build();

说明

  • 该配置会替换Cosmos DB触发器使用的序列化器,确保读取文档时不会自动将日期字符串转换为DateTime类型,保留原始字符串格式及时区信息。
  • 需确保项目中引用了Microsoft.Azure.Cosmos和Microsoft.Azure.Functions.Worker.Extensions.CosmosDB的最新兼容版本。

内容的提问来源于stack exchange,提问作者Viktoras Mickūnas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 23:10:05