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

6
我将使用Swashbuckle为我编写的ASP.NET Core API生成Swagger文档。在我的API中,我使用了很多自定义的Json转换器,因此我接收和返回的JSON并不完全符合C#类的定义。例如,我可能有一个像这样的类:
public class MyModel
{
    private MyClass complicatedField;
}

这将被序列化为

{
    "complicatedField": "String representation of the object"
}

然而,Swashbuckle 将其记录为:
{
    "complicatedField": {/*Json object of all the fields MyClass has*/}
}

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


.NET Core 还是 .NET Framework? - ATerry
@ATerry .net core。我会将其添加到问题中。 - Samuel Barr
provided both answers - ATerry
1个回答

7

如果您将类型更改为原始类型,则可以使用 MapType 。否则,应使用 SchemaFilter

.Net Framework 在启动时在某个地方调用扩展方法,例如program.cs。

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

在startup.cs文件的configure services方法中加入.Net Core
services.AddSwaggerGen(c =>
     {
          c.MapType<MyClass>(() => new Schema { Type = "string" });// add additional schema info here
          // other configs
     });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接