-3
我想知道是否有任何選項可以在反序列化時在傳入的DTO中的字符串值中'trim'和'set null as empty'?我有很多我需要做的這個字符串的屬性,所以手動這樣的過濾器每個屬性似乎過於繁瑣......ServiceStack:清理字符串值的簡單方法或選項?
我想知道是否有任何選項可以在反序列化時在傳入的DTO中的字符串值中'trim'和'set null as empty'?我有很多我需要做的這個字符串的屬性,所以手動這樣的過濾器每個屬性似乎過於繁瑣......ServiceStack:清理字符串值的簡單方法或選項?
你可以使用反射全局請求過濾器內,例如:
GlobalRequestFilters.Add((req, res, dto) => dto.SanitizeStrings());
哪裏SanitizeStrings
僅僅是一個自定義的擴展方法:
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 });
}
}
}