zoukankan      html  css  js  c++  java
  • MVC5-10 从模型验证来说内部那些事

    源码解析

    模型验证几乎在大部分的项目中都在被使用,这方面的博文教程也很多,关于那些更详细的模型验证这里就不多赘述了,主要讲解内部是如何进行验证的。

    在前几篇博文中提到了DefaultModelBinder参数的获取及绑定就是在这个时候完成的

    在绑定复杂类型(模型) 的时候,会调用OnModelUpdated方法,这个方法就是对模型的参数进行验证的image

    可以看到,这里先是拿到所有的验证,然后循环去验证,如果验证不通过则把错误消息添加到ModelState的Errors中。如果还有点迷糊的话,去想一下,我们在做自定义验证的时候需要去继承ValidationAttribute,然后重写Validate方法,而Mvc给我们预定义的也是继承ValidationAttribute方法重写Validate方法,这里其实就是拿到属性的Attribute然后循环调用Validate方法。

    protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                Dictionary<string, bool> dictionary = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
                foreach (ModelValidationResult result in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null))
                {
                    string key = CreateSubPropertyName(bindingContext.ModelName, result.MemberName);
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary[key] = bindingContext.ModelState.IsValidField(key);
                    }
                    if (dictionary[key])
                    {
                        bindingContext.ModelState.AddModelError(key, result.Message);
                    }
                }
            }

    Bind介绍

    除了模型绑定,还有一个BindAttribute。它有Exclude、Include与Prefix。可以让我们选择性的接收或忽略哪些属性,最后的Prefix不提也罢,因为用到的场景很少。

    public ActionResult Haha([Bind(Exclude = "Name,Age")] Person per)
    {
        return null;
    }

    Exclude可以让我们忽略某些属性,这个请求我传了Name、 Age和Id,但是在后台我限制了忽略Name和Age这样我拿到的只有Id了。

    image

    怎么做到的呢,其实很简单,在绑定Properties的时候会执行ShouldUpdateProperty方法,后面有一个Filter参数其实是一个委托image

    image

    propertyFilter就是GetpropertyFilter方法,这就可以看到执行了BindAttribute的 IspropertyAllowed方法,判断了是在属性是在include还是在Exclude里面,再决定是否绑定到模型上

    image

  • 相关阅读:
    requireJS的使用_API-1
    C# WebService动态调用
    Jquery 分页插件 Jquery Pagination
    脸识别API微软牛津项目
    从源码看Android中sqlite是怎么读DB的(转)
    浅谈SQL注入风险
    django
    java自动转型
    二叉搜索树(Binary Search Tree)--C语言描述(转)
    微软2014校园招聘笔试试题
  • 原文地址:https://www.cnblogs.com/LiangSW/p/6062801.html
Copyright © 2011-2022 走看看