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...
Asked
Active
Viewed 522 times
1 Answers
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