icu*_*ube -2 c# dto servicestack servicestack-text
我想知道反序列化时传入的 DTO 中的字符串值是否有任何选项可以“修剪”和“如果为空则设置为空”?我有很多字符串属性需要执行此操作,因此在每个属性的过滤器中手动执行此操作似乎太乏味了...
您可以在全局请求过滤器中使用反射,例如:
GlobalRequestFilters.Add((req, res, dto) => dto.SanitizeStrings());
Run Code Online (Sandbox Code Playgroud)
哪里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 });
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
346 次 |
| 最近记录: |