-2

I am wondering if there are any options to 'trim' and 'set null if empty' on string values in the incoming DTOs when deserializing? I have a lot of string properties I need to do this, so doing this in the filters manually for every property seems too tedious...

Scott
  • 21,211
  • 8
  • 65
  • 72
icube
  • 2,578
  • 1
  • 30
  • 63

1 Answers1

5

You can just use reflection inside a Global Request Filter, e.g:

GlobalRequestFilters.Add((req, res, dto) => dto.SanitizeStrings());

Where SanitizeStrings is just a custom extension method:

public static class ValidationUtils
{
    public static void SanitizeStrings<T>(this T dto)
    {
        var pis = dto.GetType().GetProperties();    
        foreach (var pi in pis)
        {
            if (pi.PropertyType != typeof(string)) continue;

            var mi = pi.GetGetMethod();
            var strValue = (string)mi.Invoke(dto, new object[0]);
            if (strValue == null) continue;
            var trimValue = strValue.Trim();

            if (strValue.Length > 0 && strValue == trimValue) continue;

            strValue = trimValue.Length == 0 ? null : trimValue;
            pi.GetSetMethod().Invoke(dto, new object[] { strValue });
        }
    }
}
mythz
  • 141,670
  • 29
  • 246
  • 390