C
C#3y ago
kopuo

How to use custom DateTimeConverter for selected endpoints?

I have the following converter which is responsible for reading and returning dates in UTC format:
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dateTime = DateTime.Parse(reader.GetString());

return dateTime.ToUniversalTime();
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(DateTime.SpecifyKind(value, DateTimeKind.Utc));
}
}
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dateTime = DateTime.Parse(reader.GetString());

return dateTime.ToUniversalTime();
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(DateTime.SpecifyKind(value, DateTimeKind.Utc));
}
}
I am currently using it in program.cs as follows:
.AddJsonOptions(options =>
{ options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
.AddJsonOptions(options =>
{ options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
But this causes the converter to be used throughout the system. I would like only in selected enpoints. How can I use it like this?
1 Reply
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server