You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure API Management入站策略向CosmosDB添加新条目

Azure APIM入站策略写入CosmosDB失败排查与修复

核心问题定位

从你的配置来看,主要问题集中在以下几点:

  1. Content-Type错误:CosmosDB创建文档的API要求请求头Content-Type为application/json,但当前配置使用的是application/x-www-form-urlencoded,导致CosmosDB无法解析请求体。
  2. API版本兼容性:你使用的API版本2018-12-31过于老旧,可能存在部分特性兼容问题。
  3. 文档格式合法性:需确保cosmoscontent变量存储的是合法JSON格式,且包含CosmosDB要求的唯一id字段(除非开启自动生成id)。

修正后的配置示例

<send-request mode="new" response-variable-name="cosmosstate" timeout="30" ignore-error="false">
    <set-url>https://somethin.documents.azure.com:443/dbs/tempdb/colls/tempcoll/docs</set-url>
    <set-method>POST</set-method>
    <set-header name="Authorization" exists-action="override">
        <value>@("type=aad&amp;ver=1.0&amp;sig="+context.Variables["msi-access-token-cosmos"])</value>
    </set-header>
    <set-header name="x-ms-date" exists-action="override">
        <value>@(context.Variables.GetValueOrDefault<string>("requestDateString"))</value>
    </set-header>
    <set-header name="x-ms-version" exists-action="override">
        <value>2023-03-15</value>
    </set-header>
    <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
    </set-header>
    <set-body>@((string)context.Variables["cosmoscontent"])</set-body>
</send-request>

额外排查步骤

  • 验证JSON格式:确保cosmoscontent是符合要求的JSON,例如大负载场景下的格式应为:
    {"id": "doc-123-uuid", "blobUrl": "https://yourstorage.blob.core.windows.net/container/largepayload.json", "metadata": {...}}
    
    小负载场景直接包含完整内容:
    {"id": "doc-456-uuid", "payload": "完整小负载内容", "metadata": {...}}
    
  • MSI权限验证:确认APIM的MSI已被授予CosmosDB账户的Cosmos DB Built-in Data Contributor角色,且msi-access-token-cosmos的受众为https://cosmos.azure.com/(可通过解码token验证)。
  • 错误日志排查:添加策略记录CosmosDB的响应详情,定位具体错误:
    <choose>
        <when condition="@((int)((IResponse)context.Variables["cosmosstate"]).StatusCode >= 400)">
            <log-to-eventhub logger-id="your-logger-id" partition-id="0">
                @($"CosmosDB写入错误: 状态码={(int)((IResponse)context.Variables["cosmosstate"]).StatusCode}, 响应内容={((IResponse)context.Variables["cosmosstate"]).Body.As<string>()}")
            </log-to-eventhub>
        </when>
    </choose>
    

内容的提问来源于stack exchange,提问作者PM.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:03:34