简体   繁体   中英

How to configure Json Serializer to have separate date converters for input and output parameters in web api?

I am working on web api, and I have requirements to make Json serializer to convert only dates input parameters into UTC format.

Right now I am using this code to convert:

 IsoDateTimeConverter converter = new IsoDateTimeConverter
        {
            DateTimeStyles = DateTimeStyles.AdjustToUniversal,
        };

 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);

The above configuration will be implemented on input and output date parameters.

How to configure my web api to have two date converters one for input parameters and the other for output parameters?

PS:

I want to convert date input parameters to utc but for output parameters into ISO 8601

The easiest solution that comes to my mind is to create custom DateTime converter that inherits from IsoDateTimeConverter and overrides CanWrite property so that it always returns false . In this case converter will be used only for deserializng input and never for serializing the output:

public class InputUniversalConverter : IsoDateTimeConverter
{
    public override bool CanWrite => false;

    public InputUniversalConverter()
    {
        DateTimeStyles = DateTimeStyles.AdjustToUniversal;
    }
}

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new InputUniversalConverter());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM