Tob*_*ias 3 c# json swagger asp.net-web-api2 nswag
我们正在使用 swagger/nswag 来记录 webapi 项目。
作为ActionMethods 的BodyParameters,我们使用带有后缀Command 的类,这些类包含用于例如创建在数据库中持久化的域对象的参数。
Command-Class 可能如下所示:
public class CreateChildCommand {
public Parent Parent { get; set; }
public int Position { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Position 是一个简单的 int,而 Parent 是一个持久化在数据库中的域类。可能它看起来像这样:
public class Parent {
public Guid Id { get; set; }
public string Name { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
它可以通过其 ID 从数据库加载,因此我们只需将 id 作为参数传递给 Json 中的 Command-Parameter,如下所示:
{
"Position": 3,
"Parent": "41E71207-7F1E-4895-8BCC-14E1293A7907"
}
Run Code Online (Sandbox Code Playgroud)
反序列化 Json 时,父级通过 Dao 由其 Id 加载。现在的问题是,那个 swagger/nswag 不理解那个“魔法”,并像这样显示方法的参数:
{
"Position": number,
"Parent": {
Id: "Guid",
"Name": "string",
...
}
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以告诉 swagger 替换父级的 Type 使其看起来像这样:
{
"Position": "int",
"Parent": "Guid"
}
Run Code Online (Sandbox Code Playgroud)
您可以使用JsonSchemaAttribute属性来覆盖复杂属性的架构类型:
public class CreateChildCommand {
[JsonSchema(JsonObjectType.String, Format = "guid")]
public Parent Parent { get; set; }
public int Position { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
该属性在 NJsonSchema 库中实现:https ://www.nuget.org/packages/NJsonSchema/
另一种选择是使用类型映射器将所有父类映射到字符串,请参阅https://github.com/RSuter/NJsonSchema/wiki/Type-Mappers
| 归档时间: |
|
| 查看次数: |
3147 次 |
| 最近记录: |