使用 Swashbuckle 自定义生成模型文档

Sam*_*arr 6 asp.net swagger .net-core swashbuckle

我正在使用 Swashbuckle 为我正在编写的 ASP.NET core API 生成 swagger 文档。在我的 API 中,我使用了很多自定义 Json 转换器,因此我接收和返回的 json 看起来与 C# 类的定义方式并不完全相同。例如,我可能有这样的课程:

public class MyModel
{
    private MyClass complicatedField;
}
Run Code Online (Sandbox Code Playgroud)

它将被序列化为

{
    "complicatedField": "String representation of the object"
}
Run Code Online (Sandbox Code Playgroud)

然而,Swashbuckle 将其记录为

{
    "complicatedField": {/*Json object of all the fields MyClass has*/}
}
Run Code Online (Sandbox Code Playgroud)

如何告诉 Swashbuckle 我的模型如何序列化和反序列化?

ATe*_*rry 7

您可以使用MapType,因为您要将类型更改为原始类型。否则你会使用一个SchemaFilter.

.Net Framework在启动时调用扩展方法,即。程序.cs

httpConfiguration.EnableSwagger(c =>
      {
          c.MapType<MyClass>(() => new Schema { type = "string" }); // add additional schema info here
          // other configs
      });
Run Code Online (Sandbox Code Playgroud)

.Net Core放置在startup.cs中的configure services方法中

services.AddSwaggerGen(c =>
     {
          c.MapType<MyClass>(() => new Schema { Type = "string" });// add additional schema info here
          // other configs
     });
Run Code Online (Sandbox Code Playgroud)