Azure函数COSMOS DB输出绑定 - 自定义Jsonserializersettings



i具有cosmoSDB输出绑定的Azure函数,如下:

public static class ComponentDesignHttpTrigger
{
    [FunctionName("ComponentDesignInserter-Http-From-ComponentDesign")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "fromComponentDesign")] HttpRequest request,
        [CosmosDB(
            databaseName: StorageFramework.CosmosDb.DatabaseId,
            collectionName: Storage.ComponentDesignCollectionId,
            ConnectionStringSetting = "CosmosDBConnection")] out ComponentDesign componentDesignToInsert,
        ILogger log)
    {
        var requestBody = new StreamReader(request.Body).ReadToEnd();
        componentDesignToInsert = JsonConvert.DeserializeObject<ComponentDesign>(requestBody);
        return new OkObjectResult(componentDesignToInsert);
    }
}

在此函数中,componentDesignToInsert自动序列化并在函数完成后将其放入COSMOSDB中。但是默认的序列化不会将事物放在骆驼中。对于此JSON.NET,您可以提供自定义的序列化器设置,例如:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(yourObject, settings);

,但我不确定如何将其与输出绑定集成在一起。我该如何完成?

输出绑定目前不暴露序列化器设置。

您可以做的一件事是利用您自己的自定义文档用于操作。

不过,重要的是,文档Client实例需要静态(更多详细信息https://github.com/azure/azure-functions-host/wiki/managing-connections)。

private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
private static DocumentClient documentClient => lazyClient.Value;
private static DocumentClient InitializeDocumentClient()
{
    // Perform any initialization here
    var uri = new Uri("example");
    var authKey = "authKey";
    var settings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    return new DocumentClient(uri, authKey, settings);
}
[FunctionName("ComponentDesignInserter-Http-From-ComponentDesign")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "fromComponentDesign")] HttpRequest request,
    ILogger log)
{
    var requestBody = new StreamReader(request.Body).ReadToEnd();
    var componentDesignToInsert = JsonConvert.DeserializeObject<ComponentDesign>(requestBody);
    var collectionUri = UriFactory.GetDocumentCollectionUri(StorageFramework.CosmosDb.DatabaseId, Storage.ComponentDesignCollectionId);
    await documentClient.UpsertDocumentAsync(collectionUri, componentDesignToInsert);
    return new OkObjectResult(componentDesignToInsert);
}

另一个选项是使用JsonProperty装饰类,如果适合您的方案。

相关内容

  • 没有找到相关文章

最新更新