c# - 如何从 C# 中的 Azure HTTP 触发器函数删除 CosmosDB 中的项目

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

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

对于我的 POST 操作,我使用 IAsyncCollector 对象及其 Add 方法,但看起来没有等效的删除方法。

这是我在 StackOverflow 上的第一个问题,所以如果我需要更多细节/具体信息,请告诉我:)。我对 Azure Functions 也比较陌生,因此如果我从根本上误解了某些内容,那么很高兴知道这一点。

谢谢!

最佳答案

这个问题已经得到解答here 。然而,这是使用门户的功能代码编辑器。

您可以将 DocumentClient 的实例直接绑定(bind)到您的 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

关于c# - 如何从 C# 中的 Azure HTTP 触发器函数删除 CosmosDB 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67659342/

相关文章:

c# - ASP .NET Web API 两次读取输入流

Azure Blob 存储成本分析

azure - 如何与第三方共享 Azure Function 日志

python - 无需绑定(bind)即可访问 Blob 存储?

c# - 检查数字是否是完全平方数(数字超过 15 位)

c# - 使用 PrincipalSearcher.FindAll() 时发生内存泄漏

C# 和 SQLGeometry : Combining Database Rows and WPF

Azure datafactory v2 使用 For Each 执行管道

azure - 使用 Azure Functions 中的 Google API

azure - 使用 ADF 的数据 block 或函数?