Azure Functions v4 序列化为驼峰式 Cosmos DB

Azure Functions v4 serialize to Cosmos DB in camel case

如何让 Cosmos SDK 在不在模型的所有属性中使用 [JsonPropertyName] 的情况下使用驼峰式编写文档?

例如在这个代码示例中。

        [FunctionName("CreaUsers")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users")]
                HttpRequest req,
            [CosmosDB(
                databaseName: Database.Name,
                containerName: Database.Container,
                Connection = "CosmosDBConnection")] CosmosClient client,
            ILogger log)
        {

            var container = client.GetDatabase(Database.Name).GetContainer(Database.Container);

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var user = JsonSerializer.Deserialize<User>(requestBody);

            var id = Guid.NewGuid();
            user.Id = id;
            user.UserId = id.ToString();

            var result = await container.CreateItemAsync(user, new PartitionKey(id.ToString()));

            log.LogInformation($"C# HTTP trigger function inserted one row");

            return new NoContentResult();
        }

您正在使用 4.0.0 扩展,它可以完全自定义序列化引擎。

假设您有一个 Functions Startup,您可以注入自己的自定义 ICosmosDBSerializerFactory 实现,该实现使用您自己的自定义 CosmosSerializer.

例如:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddSingleton<ICosmosDBSerializerFactory, MyCosmosDBSerializerFactory>();
    }
}

public class MyCosmosDBSerializerFactory : ICosmosDBSerializerFactory
{
    public CosmosSerializer CreateSerializer()
    {
        return new MyCustomCosmosSerializer();
    }
}

如果需要,您甚至可以使用 System.Text.Json,使用如下实现:https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson/CosmosSystemTextJsonSerializer.cs

参考:https://www.youtube.com/watch?v=w002dYaP9mw&t=735s