vendredi 29 novembre 2019

Format all dates inside IActionFilter

I have a simple requirement, but it has been over one day and i cannot figure out what would be a good approach to do it. Here is the requirement:

Whenever my service layer returns a dto, I want to be able to update all "DateTime" fields by adding one hour.

The best idea that i could of was to have Action Filter and apply it globally, so all dates are updated.

I also tried to use reflection since at runtime I will not be able to determine what Type I might have.

Here is my code:


  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");
            }
        }

The problem is at the SetValue, I am getting the error

System.Reflection.TargetException: 'Object does not match target type.'

Any help is appreciated please





Aucun commentaire:

Enregistrer un commentaire