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

使用NSwag.MSBuild生成.NET 6 API客户端时出现Pet API代码问题

问题原因与解决方案

原因

你的nswag.json配置中未指定要生成客户端的目标API的OpenAPI文档源,NSwag在找不到自定义API描述时,会默认使用Swagger官方提供的Petstore示例API(就是你看到的Pet相关接口)来生成代码。

修正方案

方案1:指定本地生成的Swagger JSON路径

先确认你的.NET 6 API已启用Swagger(项目中配置了AddSwaggerGen和UseSwagger),构建后会在输出目录生成swagger.json。修改nswag.json,在openApiToCSharpClient节点下添加openapi字段,指向你的API的swagger.json路径:

{
  "runtime": "Net60",
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": false,
      "output": "../Blah/Client.g.cs",
      "contractsOutputFilePath": "../Blah/Contracts.g.cs",
      // 新增:指向你的API的swagger.json文件路径
      "openapi": "$(ProjectDir)bin/$(Configuration)/net6.0/swagger/v1/swagger.json"
    }
  }
}

方案2:从API程序集生成OpenAPI文档再生成客户端

如果你的API存在动态路由等需要从程序集分析的内容,可先通过webApiToOpenApi生成自身的OpenAPI描述,再基于该描述生成客户端:

{
  "runtime": "Net60",
  "documentGenerator": {
    "webApiToOpenApi": {
      // 替换为你的API程序集名称
      "assemblyPaths": [
        "$(ProjectDir)bin/$(Configuration)/net6.0/YourApiName.dll"
      ],
      "documentName": "v1",
      "output": "$(ProjectDir)swagger.json"
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": null,
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": false,
      "output": "../Blah/Client.g.cs",
      "contractsOutputFilePath": "../Blah/Contracts.g.cs",
      "openapi": "$(ProjectDir)swagger.json"
    }
  }
}

额外注意事项

  • 确保API项目已正确配置Swagger服务和中间件
  • 若使用运行时URL(如http://localhost:5000/swagger/v1/swagger.json)作为openapi值,需提前启动API服务,适合开发环境测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:36:24