Joh*_*all 4 asp.net date datetime-format swagger swashbuckle
我有一个通过Swashbuckle公开的类,看起来像这样:
public class Person
{
[JsonProperty("dateOfBirth")]
[JsonConverter(typeof(DateFormatConverter))]
public System.DateTime? DateOfBirth { get; set; }
}
internal class DateFormatConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter
{
public DateFormatConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
Run Code Online (Sandbox Code Playgroud)
(该类由NSwag-studio生成)
当我使用app.UseSwagger();Swashbuckle生成Swagger合约时,结果如下所示:
"Person": {
"dateOfBirth": {
"format": "date-time",
"type": "string"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想配置Swashbuckle以识别我的DateFormatConverter班级并相应地处理格式。
我options.SchemaFilter<DateFormatSchemaFilter>()在我的Startup课程中尝试过,但是过滤器没有属性的上下文,因此除非我希望所有的 DateTime对象都是date,否则这不是一个可行的选择。
您可以通过以下方法使用iDocumentFilter 将更"date-time"改为"date":
private class Flip2DateDocumentFilter : IDocumentFilter
{
private List<string> DateTypes(Type AttribType)
{
var list = new List<string>();
foreach (var p in AttribType.GetProperties())
if (p.CustomAttributes?.Count() > 0)
list.Add(p.Name);
return list;
}
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry s, IApiExplorer a)
{
var t = typeof(Person);
if (swaggerDoc.definitions[t.Name] != null)
{
var dates = DateTypes(t);
if (dates.Count() > 0)
foreach (var p in swaggerDoc.definitions[t.Name].properties)
if (dates.Contains(p.Key) && p.Value.format == "date-time")
p.Value.format = "date";
}
}
}
Run Code Online (Sandbox Code Playgroud)
该代码中的关键var t = typeof(Person);是,该类将被爬网以查找具有CustomAttributes的日期。
当然,此代码并不旨在复制/粘贴只是您可以使用的一小部分示例 IDocumentFilter
另一个选择是使用NodaTime,然后使用NodaTime.LocalDate那些应该只是日期的属性,并在您的大张旗鼓配置中使用MapType
c.MapType<NodaTime.LocalDate>(() => new Schema { type = "string", format = "date" });
我在本示例中都使用了这两个选项:http :
//swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Date#/Date/Date_Post
后面的代码在github上:https :
//github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/App_Start/SwaggerConfig.cs
| 归档时间: |
|
| 查看次数: |
1314 次 |
| 最近记录: |