老问题了,不过还是让我自己来回答吧。我将展示基于. 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();
1条答案
按热度按时间bmvo0sr51#
老问题了,不过还是让我自己来回答吧。我将展示基于. net 6模板的代码
因此我们需要添加类型转换器(用于swagger中的正确显示)和json转换器(用于响应中的序列化)
并在应用程序中注册它们