我怎样才能让 Swashbuckle 生成带有日期(没有时间)的 Swagger 属性?

How can I get Swashbuckle to produce Swagger-properties with date (without time)?

我有一个 class 通过 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";
    }
}

(class 由 NSwag-studio 生成)

当我使用 app.UseSwagger(); 与 Swashbuckle 生成 Swagger 合约时,结果如下所示:

"Person": {
    "dateOfBirth": {
      "format": "date-time",
      "type": "string"
    }
  }
}

我想配置 Swashbuckle 以识别我的 DateFormatConverter class 并相应地处理格式。

我在 Startup class 中尝试了 options.SchemaFilter<DateFormatSchemaFilter>(),但过滤器没有 属性 的上下文,所以除非我想要 all 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";
        }
    }
}

该代码中的关键是 var t = typeof(Person);,即 class 将被抓取以查找具有 CustomAttributes 的日期。

当然,这段代码并不适用于 copy/pasting,这只是您可以使用 IDocumentFilter

做什么的一个小例子
另一种选择是使用 [NodaTime][1],然后对那些应该只是日期的属性使用 `NodaTime.LocalDate`,并在您的 swagger 配置中使用 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