[英]Using NSwag to generate a C# client incorrectly creates 2x partial classes with the same name, in the same file
I'm trying to generate an NSwag C# Client, from an OpenAPI json file.我正在尝试从 OpenAPI json 文件生成 NSwag C# 客户端。
When I do this, I do get a client file generated, but it doesn't compile.当我这样做时,我确实生成了一个客户端文件,但它没有编译。 It has created 2x partial classes in the same.cs file.
它在 same.cs 文件中创建了 2 个部分类。
Now, if I change one of these class names to anything else, the file can now compile:现在,如果我将这些 class 名称之一更改为其他名称,则该文件现在可以编译:
No errors - compiles OK.没有错误 - 编译正常。
So my question is: why is this doing it?所以我的问题是:为什么要这样做?
Here's a picture of my Swagger UI (this was generated with Swashbuckle, not NSwag):这是我的 Swagger UI 的图片(这是使用 Swashbuckle,而不是 NSwag 生成的):
So this means I have 2x controllers in the project:所以这意味着我在项目中有 2 个控制器:
Is there some trick to fixing this?有什么技巧可以解决这个问题吗?
I used the following command line, to generate the client:我使用以下命令行来生成客户端:
dotnet-openapi --updateProject.\MyProject.csproj http://localhost:5100/swagger/v1/swagger.json
Dotnet-openapi is using NSwag CSharpClientGenerator "under the hood", as far as I believe.据我所知,Dotnet-openapi 正在“幕后”使用 NSwag CSharpClientGenerator。
I'm happy to use any other tool to generate a C# client.我很高兴使用任何其他工具来生成 C# 客户端。
I do not know swagger, but as I can see in your images, one file contains the backing fields, while the other contains the properties.我不知道 swagger,但正如我在您的图像中看到的,一个文件包含支持字段,而另一个文件包含属性。 This is how code generators work in C#.
这就是代码生成器在 C# 中的工作方式。
Code generators cannot change existing code.代码生成器无法更改现有代码。 They can only create new code files.
他们只能创建新的代码文件。 Therefore, partial classes are used.
因此,使用了部分类。 Partial classes are classes that can be split among several files.
部分类是可以在多个文件中拆分的类。 But otherwise, they are exactly like other classes.
但除此之外,它们与其他类完全一样。
Now, given a set of fields, a code generator can automatically create properties for these fields (it can do many other things, but this is what happens in this case), but it can only do this by creating another file.现在,给定一组字段,代码生成器可以自动为这些字段创建属性(它可以做许多其他事情,但在这种情况下会发生这种情况),但它只能通过创建另一个文件来做到这一点。
The pairs of files with the same partial class are okay.具有相同部分 class 的文件对是可以的。
See also: Introducing C# Source Generators另请参阅: 介绍 C# 源生成器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.