c# - 如何查找匿名对象的所有 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);
}
}
解决方案
推荐阅读
- apache-spark - Databricks Spark Dataframe - 不匹配的模式 - 控制错误
- vue.js - 有没有办法在 vuetify 中输入预定义转换的钩子?
- javascript - 记录传入消息 twilio node.js
- tbb - 错误:内核函数、SYCL、DPCPP 不允许隐式捕获“this”
- discord.py - 我用一个 api 解决了这个问题,我用它来显示我在 youtube 上有多少个订阅者
- css - 使用 service worker 预缓存内容后,css 通过磁盘缓存而不是 service worker 缓存加载
- google-chrome-devtools - 重用 Chrome Devtools 控制台自动完成
- amazon-web-services - AWS Glue 等效于 EMRFS 角色映射
- python - 如何测试python中离散和连续随机变量的相等性?
- python - python中的数值导数