Azure 函数 Cosmos DB 输出绑定 - 自定义 JsonSerializerSettings

Sco*_*y H 7 azure json.net azure-functions azure-cosmosdb azure-functions-core-tools

我有一个带有 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这个函数componentDesignToInsert中,函数执行完成后会自动序列化并放入 CosmosDB。但是默认的序列化不会把东西放在camelCase中。为此,Json.NET 允许您提供自定义序列化程序设置,如下所示:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JsonConvert.SerializeObject(yourObject, settings);
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将它与我的输出绑定集成。我怎样才能做到这一点?

Mat*_*nta 3

输出绑定此时不会公开序列化器设置。

不过,您可以做的一件事是利用您自己的自定义 DocumentClient 进行操作。

但一件重要的事情是 DocumentClient 实例必须是静态的(更多详细信息请参见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);
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是根据您的场景来装饰该类JsonProperty

  • 不。绑定做了类似的事情,它在下面维护一个静态 DocumentClient,只是不公开它以使其更加用户友好。但绑定不具有完全的自定义功能。 (2认同)