Add DateOnly, TimeOnly support

This commit is contained in:
ngfrolov 2022-05-31 12:30:03 +05:00
parent c568fafa8f
commit 58b0ae6a80
3 changed files with 54 additions and 5 deletions

View File

@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DateOnlyTimeOnly.AspNet.Swashbuckle" Version="1.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="6.0.1" />
<PackageReference Include="protobuf-net" Version="3.0.101" />

View File

@ -0,0 +1,46 @@
using System;
using System.ComponentModel;
using System.Globalization;
namespace AsbCloudWebApi.Converters
{
#nullable enable
public class DateOnlyTypeConverter : 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)
{
if (value is string str)
{
return TimeOnly.Parse(str);
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (destinationType == typeof(string) && value is TimeOnly date)
{
return date.ToString("O");
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#nullable disable
}

View File

@ -19,17 +19,19 @@ namespace AsbCloudWebApi
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(new System.Action<Microsoft.AspNetCore.Mvc.JsonOptions>(opts =>
services.AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters())
.AddJsonOptions(new System.Action<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
opts.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals | System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;
options.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals | System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;
options.UseDateOnlyTimeOnlyStringConverters();
}))
.AddProtoBufNet(); //adds mediaType "application/protobuf"
.AddProtoBufNet()
; //adds mediaType "application/protobuf"
ProtobufModel.EnshureRegistered();
services.AddSwagger();
services.AddInfrastructure(Configuration);
services.AddJWTAuthentication();