Passing UTC DateTime to Web API HttpGet Method results in local time

前端 未结 5 863
失恋的感觉
失恋的感觉 2020-12-02 15:39

I\'m trying to pass a UTC date as a query string parameter to a Web API method. The URL looks like

/api/order?endDate=2014-04-01T00:00:00Z&zoneId=4
         


        
5条回答
  •  温柔的废话
    2020-12-02 16:03

    If you want the conversion to be transparent, then you could use a custom TypeConverter:

    public sealed class UtcDateTimeConverter : DateTimeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            return ((DateTime)base.ConvertFrom(context, culture, value)).ToUniversalTime();
        }
    }
    

    and wire it up using:

    TypeDescriptor.AddAttributes(typeof(DateTime), new TypeConverterAttribute(typeof(UtcDateTimeConverter)));
    

    Then the query string parameter will be instantiated as DateTimeKind.Utc.

提交回复
热议问题