【发布时间】:2022-01-01 09:07:03
【问题描述】:
Model Validation Extension code failed
大家好
我想创建一个静态基础方法,而不是为每个模型单独编写一个验证方法,但它没有发生。
有办法吗?还是需要尝试其他方法?
控制器
[HttpPost]
public IActionResult SaveMember(MemberPostModel postedMember)
{
if (postedMember.Validate()) return null;
// other code ...
}
型号
public class MemberPostModel : PostModelBase<MemberPostModel>, IDto
{
public int Id { get; set; }
// other properties...
}
用于验证的基本模型
public static class PostModelBase<TPostModel> where TPostModel : IDto
{
public static bool Validate(this TPostModel postModel)
{
foreach (var prop in postModel.GetType().GetProperties())
{
if (prop.PropertyType == typeof(string))
{
var length = prop.GetValue(postModel)?.ToString().Length.ToInt32();
var attr = prop.GetPropertyCustomAttribute<StringLengthAttribute>();
if (attr == null) continue;
if (attr.MaximumLength == length) continue;
else return false;
}
}
return true;
}
}
【问题讨论】:
-
嗨,我认为首先你应该放弃使用静态关键字另一方面,你可以使用中间件或 AOP 来代替,你可以在这里创建一个抽象类并在需要时移动保存方法更改,您可以覆盖您的代码。此外,您可以使用一些属性或流畅的 API 最好的问候
-
感谢您的建议@malikmasis。我想我需要做研究并了解中间件和 AOP 方法。 :)
标签: c# inheritance model static extension-methods