【问题标题】:How to delete an item in a CosmosDB from an Azure HTTP Trigger function in C#如何从 C# 中的 Azure HTTP 触发器函数中删除 CosmosDB 中的项目
【发布时间】:2021-08-12 00:10:52
【问题描述】:

我有一个 Blazor、Azure Stacic Web 应用程序,它使用 Azure HTTP 触发器函数在 Azure CosmosDB 上执行 CRUD 操作。我不确定如何从数据库中删除单个项目? GET 和 POST 操作似乎对 HTTP 触发器函数有很好的记录,但我正在努力找出如何仅对单个项目执行 DELETE。我有项目的 id 属性,所以会选择要通过它的 id 删除的项目。

对于我的 POST 操作,我使用 IAsyncCollector 对象和它的 Add 方法,但似乎没有等效的删除方法。

这是我在 StackOverflow 上的第一个问题,所以如果我需要更多细节/细节,请告诉我 :)。我对 Azure Functions 也比较陌生,所以如果我从根本上误解了某些东西,那就太好了。

谢谢!

【问题讨论】:

  • 欢迎来到 Stack Overflow,马特!请编辑您的问题并包含您迄今为止编写的代码。这将有助于人们更好地了解您的问题。
  • 谢谢@GauravMantri,这会有所帮助,不是吗!下次我一定会把目前写的代码放上来。

标签: c# azure azure-functions blazor-webassembly azure-static-web-app


【解决方案1】:

这已经回答here。但是,这是使用门户的 func 代码编辑器。

您可以改为将DocumentClient 的实例直接绑定到您的 HTTP 触发器函数:

[FunctionName("Function1")]
public async Task<IActionResult> DeleteProduct(
    [HttpTrigger(
        authLevel: AuthorizationLevel.Anonymous,
        methods: "delete",
        Route = "products/{productId}")] HttpRequest request,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "products")] DocumentClient client,
    Guid productId)
{
    Uri productUri = UriFactory.CreateDocumentUri("my-database", "products", productId.ToString());
    PartitionKey partitionKey = new PartitionKey("my-partition-key");
    RequestOptions requestOptions = new RequestOptions { PartitionKey = partitionKey };

    ResourceResponse<Document> response = await client.DeleteDocumentAsync(productUri, requestOptions);
    // Use response for something or not...

    return new NoContentResult();
}

该示例要求您使用键“CosmosDBConnection”配置 Cosmos DB 连接字符串。这必须在local.settings.json 中设置以进行本地开发:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "CosmosDBConnection": "my-cosmos-db-connection"
  }
}

在你的函数应用的应用程序设置中。

您需要以下软件包才能使其工作:

  • Microsoft.Azure.Cosmos
  • Microsoft.Azure.WebJobs.Extensions.CosmosDB

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多