我目前在 apim 后面托管 serval api。我现在计划公开文档并希望以编程方式执行此操作,因此我的问题是:
是否可以制定一个全局策略来拦截到
../<api-service-id>/openapi.json
的流量并从请求的端点返回文档,而无需为其创建专用的 API 路由?
下面的代码似乎对我没有任何作用。
<policies>
<inbound>
<!--Dynamically call the APIM Management API-->
<choose>
<when condition="@(context.Request.OriginalUrl.Path.EndsWith("/openapi.json", StringComparison.OrdinalIgnoreCase))">
<send-request mode="new" response-variable-name="result" timeout="10" ignore-error="true">
<set-url>@("/subscriptions/my-sub/resourceGroups/my-reg/providers/Microsoft.ApiManagement/service/my-service" + "/apis/" + context.Request.MatchedParameters.GetValueOrDefault("api-id","") + "?export=true&format=openapi&api-version=2022-09-01-preview")</set-url>
<set-method>GET</set-method>
<authentication-managed-identity resource="https://management.azure.com/" />
</send-request>
<!--Return the response-->
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@((string)(((IResponse)context.Variables["result"]).Body.As<JObject>()["value"]))</set-body>
</return-response>
</when>
</choose>
</inbound>
<backend>
<forward-request />
</backend>
<outbound />
<on-error />
</policies>
我在全局级别使用以下策略来获取 OpenAPI 文档并动态传递 apiId。
添加策略如下图-
<policies>
<inbound>
<send-request mode="new" response-variable-name="result" timeout="10" ignore-error="false">
<set-url>@("https://management.azure.com/subscriptions/0e8****5e7c/resourceGroups/DefaultResourceGroup/providers/Microsoft.ApiManagement/service/afreeen-apimgmt/apis/" + context.Api.Id + "?export=true&format=openapi&api-version=2022-09-01-preview")</set-url>
<set-method>GET</set-method>
<authentication-managed-identity resource="https://management.azure.com/" />
</send-request>
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@(((IResponse)context.Variables["result"]).Body.As<JObject>().ToString())</set-body>
</return-response>
</inbound>
<backend>
<forward-request />
</backend>
<outbound />
<on-error />
</policies>
通过单击“Azure 角色分配”,将资源组级别的 RBAC 角色授予托管身份 API 管理服务读取器。
追踪-
回应-