首页 > 解决方案 > 如何查找匿名对象的所有 DateTime 属性?

问题描述

我想在服务器端代码中处理它们之前将从客户端收到的所有日期转换为 UTC。我正在考虑使用 ActionFilter,我想从请求有效负载中找到所有日期字段并将它们转换为 UTC 日期。我知道反射有助于通过它的类型查找属性,但它在匿名对象的情况下不起作用。

下面是我的代码示例

        //convert body to object
        var result = JsonConvert.DeserializeObject<object>(rawRequest);
        var type = result.GetType();

        //get collection of properties from object
        var properties = result.GetType().GetProperties();
        foreach (var property in properties)
        {
            //if data type is DateTime then convert into UTC
            if (property.PropertyType == typeof(DateTime?) || property.PropertyType == typeof(DateTime))
            {
                string TimeZoneId = "India Standard Time";
                if (HttpContext.Current.Request.Headers["TimeZoneId"] != null)
                {
                    TimeZoneId = HttpContext.Current.Request.Headers.GetValues("TimeZoneId").FirstOrDefault();
                }
                var localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId);
                var Date = DateTime.SpecifyKind(((DateTime?)property.GetValue(result, null)) ?? DateTime.Now, DateTimeKind.Unspecified);
                var localTime = TimeZoneInfo.ConvertTimeToUtc(Date, localTimeZone);
            }
        }

标签: c#reflectiontimezoneutcpropertyinfo

解决方案


推荐阅读