bestsource

ASP의 Date Time 포맷.시스템을 사용한NET Core 3.0Text.Json

bestsource 2023. 2. 23. 22:57
반응형

ASP의 Date Time 포맷.시스템을 사용한NET Core 3.0Text.Json

에서 웹 API를 이행하고 있습니다.NET Core 2.2~3.0을 사용하고 싶다.System.Text.Json·사용시Newtonsoft포맷을 할 수 있었습니다.DateTime다음 코드를 사용합니다.어떻게 하면 같은 일을 할 수 있을까요?

.AddJsonOptions(options =>
    {
        options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
        options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";
    });

커스텀 포메터로 해결.Panagiotis에게 제안해 주셔서 감사합니다.

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));
        return DateTime.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
    }
}


// in the ConfigureServices()
services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
     });

Core 3으로 이행할 때 시스템을 교체해야 했습니다.Text.Json은 다음을 통해 Newtonsoft를 다시 사용합니다.

services.AddControllers().AddNewtonsoftJson();

그러나 Angular 앱에서도 UTC 날짜에 문제가 있어 UTC 날짜를 취득하기 위해 이를 추가해야 했습니다.

services.AddControllers().AddNewtonsoftJson(
       options => options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);

이 경우 다음을 수행할 수 있습니다.

services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
        options.SerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ";
    });

효과가 있고 도움이 됐으면 좋겠는데...

이는 다른 사용자가 제안한 것과 거의 동일하지만 형식 문자열을 속성 내의 매개 변수로 사용하기 위한 추가 단계가 있습니다.

포메터:

public class DateTimeFormatConverter : JsonConverter<DateTime>
{
    private readonly string format;

    public DateTimeFormatConverter(string format)
    {
        this.format = format;
    }

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.ParseExact(
            reader.GetString(),
            this.format,
            CultureInfo.InvariantCulture);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        ArgumentNullException.ThrowIfNull(writer, nameof(writer));

        writer.WriteStringValue(value
            .ToUniversalTime()
            .ToString(
                this.format,
                CultureInfo.InvariantCulture));
    }
}

부터JsonConverterAttribute봉인되어 있지 않습니다.이렇게 할 수 있습니다.

public sealed class JsonDateTimeFormatAttribute : JsonConverterAttribute
{
    private readonly string format;

    public JsonDateTimeFormatAttribute(string format)
    {
        this.format = format;
    }

    public string Format => this.format;

    public override JsonConverter? CreateConverter(Type typeToConvert)
    {
        return new DateTimeFormatConverter(this.format);
    }
}

이 asp.net 코어 날짜의 시리얼화/디시리얼화의 덤프통 화재는 Date의 덤프통 화재를 보면 이해하기 쉬울 수 있습니다.해석() 및 날짜.ParseExact() 입니다.javascript와 날짜를 주고받기 때문에 포맷을 하고 싶지 않습니다.UTC에서 DateTime과 ISO 8601 간에 투명하게 직렬화역직렬화하기만 하면 됩니다.

이것이 기본값이 아니며 쉬운 구성 옵션이 없으며 솔루션이 매우 펑키하고 취약하다는 것은 신뢰성을 떨어뜨립니다.이것이 현재 나에게 효과가 있는 것입니다.D에 근거하고 있습니다.영어 쓰기 답변과 읽기 답변 링크 답변, 그리고답변을 사용하여 JsonDocument에 올바르게 액세스...

모델 바인딩의 덤프터 화재에 대한 업데이트입니다.쿼리 문자열 파싱의 쓰레기통 화재는 이쪽입니다.

// in Startup.cs ConfigureServices()

services.AddMvc().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new UtcDateTimeConverter());
});


public class BobbyUtcDateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (var jsonDoc = JsonDocument.ParseValue(ref reader))
        {
            var stringValue = jsonDoc.RootElement.GetRawText().Trim('"').Trim('\'');
            var value = DateTime.Parse(stringValue, null, System.Globalization.DateTimeStyles.RoundtripKind);
            return value;
        }
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture));
    }
}

현재 asp.net 6/7에서 다음을 설정하시면DateTime.Kind로.Utc그러면 DateTime 객체가 UTC 시간대를 나타내는 말미에 'Z'가 붙어 시리얼화 됩니다.

데이터가 efcore에서 가져온 경우 다음과 같이 모든 DateTime 데이터를 UTC로 처리하도록 지정할 수 있습니다.

언급URL : https://stackoverflow.com/questions/58102189/formatting-datetime-in-asp-net-core-3-0-using-system-text-json

반응형