asp.net - 我怎样才能让 Swashbuckle 产生带有日期(没有时间)的 Swagger 属性?

标签 asp.net date swagger datetime-format 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";
    }
}

(该类由 NSwag-studio 生成)

当我使用 app.UseSwagger();使用 Swashbuckle 生成 Swagger 合约,结果如下所示:
"Person": {
    "dateOfBirth": {
      "format": "date-time",
      "type": "string"
    }
  }
}

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

我试过 options.SchemaFilter<DateFormatSchemaFilter>()在我的 Startup类,但过滤器没有属性的上下文,所以除非我希望所有 DateTime 对象都是 date ,这不是一个可行的选择。

最佳答案

以下是如何更改 "date-time""date"使用 iDocumentFilter:

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);这是将被爬行以查找带有 CustomAttributes 的日期的类。

当然,此代码代码并非用于复制/粘贴,只是您可以使用 IDocumentFilter 执行的操作的一个小示例。

另一种选择是使用 NodaTime然后使用 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

关于asp.net - 我怎样才能让 Swashbuckle 产生带有日期(没有时间)的 Swagger 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320611/

相关文章:

asp.net - ASP .net 验证

c# - 如何解决 Swagger 错误 "instance type (string) does not match any allowed primitive type..."

jquery - 如何使用 jQuery 访问 Bool 值

c# - 将文件写入响应后关闭弹出窗口

语言环境的 Java 日期格式

date - 确定所选日期的数量

android - 在 Android 中将字符串更改为日期

api - 在单独的目录下使用swaggydoc在具有相同 Controller 名称的grails上记录API的多个版本

swagger - OpenAPI:必填字段、可选字段和未指定字段的混合

asp.net - 项目在本地运行但在 Azure 上崩溃