.NET核心:参数列表中的Edm.Date用法生成错误的Swagger文档

t40tm48m  于 2022-11-23  发布在  .NET
关注(0)|答案(1)|浏览(105)

假设该控制器

[HttpGet("byDate")]
    public IActionResult Send([Required] [FromQuery] Date date)
    {
        return Ok(date);
    }

我希望得到字符串的普通bindind(例如pass“2020-12-31),而swagger使用3个参数生成文档- Year、Month和Day。
允许这个对象作为纯字符串传递的最常见的方法是什么?

bmvo0sr5

bmvo0sr51#

老问题了,不过还是让我自己来回答吧。我将展示基于. net 6模板的代码
因此我们需要添加类型转换器(用于swagger中的正确显示)和json转换器(用于响应中的序列化)

public class DateTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }

        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        return Date.Parse(value as string);
    }
}

public class DateConverter : JsonConverter<Date>
{
    public override bool CanConvert(Type objectType) => typeof(Date) == objectType;

    public override Date Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
        reader.GetDateTime();

    public override void Write(Utf8JsonWriter writer, Date value, JsonSerializerOptions options) =>
        writer.WriteStringValue(value.ToString());
}

并在应用程序中注册它们

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers() .AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new DateConverter());
});
TypeDescriptor.AddAttributes(typeof(Date), new TypeConverterAttribute(typeof(DateTypeConverter)));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(opts =>
{
    opts.MapType(typeof(Date), () => new OpenApiSchema { Type = "string", Format = "date" });
    opts.MapType(typeof(Date?), () => new OpenApiSchema { Type = "string", Format = "date" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

相关问题