模型驗證擴展代碼失敗
嗨,大家好
我想創建一個靜態基本方法,而不是為每個模型單獨撰寫一個驗證方法,但它沒有發生。
有辦法嗎?還是有必要嘗試另一種方法?
控制器
[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;
}
}
uj5u.com熱心網友回復:
為什么它必須是靜態的?如果您簡單地洗掉 static 關鍵字,這看起來應該可以作業。C# 中類的 static 關鍵字不會做任何事情,除了阻止您創建非靜態方法。在我看來,為您的模型設定單獨的驗證器是有意義的。如果您將來需要檢查一些其他財產怎么辦?
uj5u.com熱心網友回復:
您不能繼承靜態類,因為它們是密封的和抽象的。如果您需要繼承一個類,則需要使其成為非靜態的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369635.html
