【发布时间】:2017-04-17 21:39:54
【问题描述】:
我正在使用以下数据合约的更复杂版本,但这应该足以作为示例:
using System;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
[DataContract(Namespace = "https://schemas.company.name/api-name/")]
public class Subscription
{
[DataMember(IsRequired = true)]
public long SubscriptionID { get; set; }
[DataMember(IsRequired = true)]
public long ProductID { get; set; }
[DataMember(IsRequired = true)]
public long AccountID { get; set; }
[DataMember(IsRequired = true), DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[DataMember(IsRequired = true), DataType(DataType.Date)]
public DateTime EndDate { get; set; }
}
Swashbuckle 为上述数据合约生成的 swagger JSON 定义变成了这样:
...
"Subscription": {
"required": ["subscriptionID", "productID", "accountID", "startDate", "endDate"],
"type": "object",
"properties": {
"subscriptionID": {
"format": "int64",
"type": "integer"
},
"productID": {
"format": "int64",
"type": "integer"
},
"accountID": {
"format": "int64",
"type": "integer"
},
"startDate": {
"format": "date-time",
"type": "string"
},
"endDate": {
"format": "date-time",
"type": "string"
}
}
},
...
但是,您会注意到 JSON definitions.Subscription.properties.startDate.format 是 "date-time",但 C# 代码中的 DateTypeAttribute 注释是 DataType.Date,而不是 DataType.DateTime。
如何让 Swashbuckle 在生成 swagger 文件时尊重 System.ComponentModel.DataAnnotations.DataTypeAttribute?或者更具体地说,使使用[DataType(DataType.Date] 注释的类属性生成format 的"date" 的招摇?
我希望这是所有类的默认行为,因为我有太多需要硬编码特定类属性的详细信息,并且是使用 Swashbuckle 根据同一命名空间内的其他注释生成 swagger JSON 的重点(如System.ComponentModel.DataAnnotations.StringLengthAttribute)。
我最初的尝试是尝试在我的 Startup.cs 中使用 ISchemaFilter,例如:
services.AddSwaggerGen(options =>
{
...
options.SchemaFilter<DataTypeSchemaFilter>();
...
});
过滤器类实现应用的地方:
public class DataTypeSchemaFilter : ISchemaFilter
{
public void Apply(Schema model, SchemaFilterContext context)
{
???
}
}
但是,我看不到使用提供的 Schema model 和 SchemaFilterContext context 参数从过滤器中调查类属性属性的能力。
如前所述,我知道 Swashbuckle 在处理类属性时会查看同一命名空间中的属性,所以我希望有人知道我可以在哪里绑定到 Swashbuckle 并执行类似的任务。
【问题讨论】:
标签: c# swagger swagger-2.0 swashbuckle