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

如何使用Azure SDK for .NET导出APIM的OpenAPI定义?

使用Azure SDK for .NET导出APIM的OpenAPI定义

要实现和你提供的PowerShell命令相同的功能,你需要利用Azure.ResourceManager.ApiManagement包中ApiResource的导出方法,具体步骤和代码如下:

前提准备

确保已安装最新版的Azure.ResourceManager.ApiManagement NuGet包。

实现代码

假设你已经获取到ApiManagementServiceResource实例,可通过以下代码遍历并导出每个API的OpenAPI JSON定义:

using Azure.ResourceManager.ApiManagement;
using Azure.ResourceManager.ApiManagement.Models;
using System.IO;

// 替换为你的导出目录路径
string openApiExportDirectory = @"C:\your-export-path";
Directory.CreateDirectory(openApiExportDirectory);

// 遍历所有API资源
await foreach (ApiResource apiResource in apiManagementServiceResource.GetApis().GetAllAsync())
{
    // 导出API为OpenAPI JSON格式
    var exportResult = await apiResource.GetApiExportAsync(
        WaitUntil.Completed,
        ExportFormat.OpenApiJson
    );

    // 读取导出内容并保存到文件
    using Stream contentStream = exportResult.Value.Content;
    using StreamReader reader = new StreamReader(contentStream);
    string openApiContent = await reader.ReadToEndAsync();
    
    string exportFilePath = Path.Combine(openApiExportDirectory, $"{apiResource.Data.Name}.json");
    await File.WriteAllTextAsync(exportFilePath, openApiContent);
}

关键说明

  • GetApiExportAsync是ApiResource的核心方法,对应APIM的导出API规范操作,参数ExportFormat.OpenApiJson与PowerShell中的SpecificationFormat OpenApiJson完全对应。
  • 导出结果的Content属性是包含OpenAPI定义的数据流,读取后即可保存为本地JSON文件。
  • 需要确保当前使用的Azure身份拥有APIM的读取/导出权限(如API Management Service Reader或更高权限角色)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:13:16