Skip to content

通过OpenAPI和Visual Studio生成客户端代码

L edited this page Apr 6, 2023 · 6 revisions

根据Generating HTTP API clients using Visual Studio Connected Services,我们得知,我们可以通过Visual Studio连接API,进而自动生成对应的客户端代码。

首先,我们启动一个本地服务DotNet6WebAPI。代码可以参考这里
1
这里我们获得了一个API地址:http://localhost:5137/swagger/index.html。 它的schema地址为http://localhost:5137/swagger/v1/swagger.json。这个地址是我们后面需要用到的地址。

然后我们创建一个客户端项目DotNet6WebAPI.Client
通过Visual Studio创建一个客户端代码:
右键项目,添加连接服务。
2
点击加号添加连接服务。这里支持的服务有OpenAPIgPRCWCF服务
3
4
这里我们可以选择一个swagger.json文件,也可以输入一个可访问的在线swagger文档。
5
生成成功。
6
接着我们就可以正常使用它了:

using TestClientNamespace;

HttpClient httpClient = new HttpClient();
TestClient client = new TestClient("http://localhost:5137/", httpClient);
var enums = await client.GetEnumAsync();
Console.WriteLine(enums);

这里我们访问GetEnum接口,只需要调用相应的GetEnumAsync方法即可。如果存在参数,则方法会列出参数列表。
返回结果如下:
8

当API发生更新时,我们也可以通过Visual Studio更新客户端代码。
7

补充说明

除了通过VS的UI进行设置,我们也可以编辑.csproj项目文件,进行更加详细的设置

<OpenApiReference Include="OpenAPIs\openapi.v1.json" CodeGenerator="NSwagCSharp" Namespace="YourNamaspace" ClassName="{controller}Client">
  <SourceUri>https://localhost:5000/swagger/v1/swagger.json</SourceUri>
</OpenApiReference>

这里Include设置了json文件的位置;
CodeGenerator设置生成C#的代码;
Namespace设置命名空间;
ClassName设置生成的客户端的名称,这里使用{controller}Client,则会根据服务端的对应Controller生成客户端Client;
SourceUri设置检查更新json文件的路径。
我们还可以添加设置输出文件的位置:

<ApiDocs Include="OpenAPIs\openapi.v1.json" DocName="v1" CsharpClientOutDir="OpenAPIs\YourClient.g.v1.cs" ClientNamespace="YourNamaspace" />

CsharpClientOutDir可以指定输出文件位置及文件名。
结合起来的设置如下:

<ItemGroup>
  <OpenApiReference Include="OpenAPIs\openapi.v1.json" CodeGenerator="NSwagCSharp" Namespace="YourNamaspace" ClassName="{controller}Client">
    <SourceUri>https://localhost:5000/swagger/v1/swagger.json</SourceUri>
  </OpenApiReference>
</ItemGroup>

<ItemGroup>
  <ApiDocs Include="OpenAPIs\openapi.v1.json" DocName="v1" CsharpClientOutDir="OpenAPIs\YourClient.g.v1.cs" ClientNamespace="YourNamaspace" />
</ItemGroup>

示例代码

DotNet6WebAPI.Client
DotNet6WebAPI

参考资料

Generating HTTP API clients using Visual Studio Connected Services

Clone this wiki locally