C#C
C#4y 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));
        }
    }

I am currently using it in program.cs as follows:

.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?
Was this page helpful?