.net-core - 使用带有接口的 OpenApi 客户端 .NET Core
问题描述
外面的人一定已经遇到过这种情况......
我创建了一个 WebApi 解决方案,实现了招摇,完整的文档,整个 9 码!
- 当我运行我的 web api 解决方案时,请查看 swagger 输出(并且我已经测试了端点,一切正常)
- 我可以看到招摇定义:https://localhost:5001/swagger/v1/swagger.json
现在,我想将此 Api 作为我的 Web 应用程序上的连接服务使用。因此,请遵循在线的每个教程:
这会在我的解决方案中生成一个部分类(MyTestApiClient)
public parial class MyTestApiClient
{
// auto generated code
}
下一步,在 Startup.cs 中注入服务
services.AddTransient(x =>
{
var client = new MyTestApiClient("https://localhost:5001", new HttpClient());
return client;
});
然后,将该类注入到某个被消耗的类中,这一切都有效
public class TestService
{
private readonly MyTestApiClient _client; // this is class, not an interface -> my problem
public TestService(MyTestApiClient client)
{
_client = client;
}
public async Task<int> GetCountAsync()
{
return _client.GetCountAsync();
}
}
所以到目前为止一切都有效。但是,这个生成的 OpenApi 客户端没有用于 DI 和单元测试的接口。
我通过创建一个本地接口 IMyTestApiClient 来解决这个问题,并将其添加到生成的类 (MyTestApiClient) 中。我的 WebApi 中只有 1 个端点,所以必须在我的界面上声明它。
public parial class MyTestApiClient : IMyTestApiClient
{
// auto generated code
}
public interface IMyTestApiClient
{
// implemented in generated MyTestApiClient class
Task<int> GetCountAsync();
}
services.AddTransient<IMyTestApiClient, MyTestApiClient>(x =>
{
IMyTestApiClient client = new MyTestApiClient("https://localhost:5001", new HttpClient());
return client;
});
public class TestService
{
private readonly IMyTestApiClient _client; // now injecting local interface instead of the generated class - great success
public TestService(IMyTestApiClient client)
{
_client = client;
}
public async Task<int> GetCountAsync()
{
return _client.GetCountAsync();
}
}
但这是一个不好的方法,因为它让我手动创建一个接口并显式声明我想要使用的方法。此外,每次我的 Api 更新时,我都必须调整我的本地界面。
所以提问时间: 如何添加自动生成接口的 OpenApi 服务参考?提前感谢您提供任何帮助以找到可行的解决方案。
解决方案
您可能已经找到了答案,但我遇到了同样的问题,并通过在我的 .csproj 中的 OpenAPI 参考的选项部分添加 /GenerateClientInterfaces:true 来解决它:
<OpenApiReference Include="api.json" CodeGenerator="NSwagCSharp" Namespace="MyNamespace" ClassName="MyClassName">
<SourceUri>https://localhost:7040/swagger/v1/swagger.json</SourceUri>
<OutputPath>MyClient.cs</OutputPath>
<Options>/GenerateClientInterfaces:true</Options>
</OpenApiReference>
推荐阅读
- selenium - 我在抓取向下滚动页面时遇到错误
- python - Tkinter/Python Canvas 不显示来自 OpenCV 的图像
- c++ - 无法在头文件中使用类中的类成员(Visual Studio)
- javascript - pixi js中缩放和旋转舞台上的按钮不响应触摸事件
- angular - 无法绑定到“值”,因为它不是“ngs-code-editor”的已知属性
- angular - Angular:使用 Observable 显示和搜索数据
- javascript - 如何无限地选中和取消选中复选框?
- python - 使用 TensorFlow 2.0 (python 3) 获取卷积神经网络 (CNN) 的数据集
- azure - 导出多个 Azure AD 组成员
- bash - 如何在 Docker 容器中运行 bash 终端以及其他命令?