繁体   English   中英

格式化 IActionFilter 中的所有日期

[英]Format all dates inside IActionFilter

我有一个简单的要求,但已经过了一天,我无法弄清楚什么是好的方法。 这是要求:

每当我的服务层返回一个 dto 时,我希望能够通过添加一小时来更新所有“DateTime”字段。

我能做的最好的想法是拥有 Action Filter 并在全球范围内应用它,因此所有日期都会更新。

我还尝试使用反射,因为在运行时我将无法确定我可能拥有的类型。

这是我的代码:


  public class dtFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            var datetimesKeyValue = context.ModelState.Keys;//.Result;//.ActionArguments.Where(p => p.Value is DateTime).ToList();

            var result = ((context.Result as ObjectResult)?.Value as ApiOkResponse)?.Result;

            var resulType = result.GetType();

            var resultProperties = resulType.GetProperties();


            foreach (var resultProperty in resultProperties)
            {
                Type mainProperty = resultProperty.PropertyType;
                if (mainProperty.IsClass)
                {
                    GetPropertiesAndUpdateDate(mainProperty, resultProperty.PropertyType);

                }
            }

        }

        private static void GetPropertiesAndUpdateDate(Type mainProperty, Type resultProperty)
        {
            var properties = mainProperty.GetProperties();
            foreach (var propertyInfo in properties)
            {
                if (propertyInfo.PropertyType.IsClass)
                {
                    GetPropertiesAndUpdateDate(propertyInfo.PropertyType, propertyInfo.DeclaringType);
                }

                if (propertyInfo.PropertyType.Name == "DateTime")
                {
                    PropertyInfo fieldPropertyInfo = mainProperty.GetProperties()
                        .FirstOrDefault(f => string.Equals(f.Name, propertyInfo.Name, StringComparison.CurrentCultureIgnoreCase));

                    fieldPropertyInfo.SetValue(resultProperty, DateTime.Now);
                }
                Debug.Write("s");
            }
        }

问题出在 SetValue,我收到错误

System.Reflection.TargetException:“对象与目标类型不匹配。”

请提供任何帮助

您将PropertyInfo对象作为SetValue的第一个参数传递。 但是,第一个参数应该是您要为其设置属性值的对象。

如果您在对象MyClass中有一个DateTime Target属性,您将调用SetValue为:

var propertyInfo = myClassInstance.GetType().GetProperty("Target");
propertyInfo.SetValue(myClassInstance, DateTime.Now, null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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