【问题标题】:There was no Static Base method (Model Validation Extension code failed)没有静态基础方法(模型验证扩展代码失败)
【发布时间】: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


【解决方案1】:

为什么它必须是静态的?如果您只是删除 static 关键字,这看起来应该可以工作。 C# 中类上的 static 关键字没有任何作用,除了阻止您创建非静态方法。 在我看来,为您的模型设置单独的验证器是有意义的。如果您将来需要检查一些其他属性怎么办?

【讨论】:

  • 那么就是这样使用的linkimg
【解决方案2】:

您不能继承静态类,因为它们是密封的和抽象的。如果你需要继承一个类,你需要使它成为非静态的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多