为什么永远不会调用Custom DataAnnotationsModelMetadataProvider的CreateMetadata?

时间:2018-02-09 14:44:28

标签: c# asp.net-mvc asp.net-mvc-5

我通过继承DataAnnotationsModelMetadataProvider并覆盖CreateMetadata方法创建了自定义提供程序:

public class CustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, 
        Type containerType, Func<object> modelAccessor, 
        Type modelType, string propertyName)
    {
        //... code not included for brevity but execution never gets here
    }
}

然后我在Global.asax班级MvcApplication内注册了它:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        // Other code...
        System.Web.ModelBinding.ModelMetadataProviders.Current = 
            new CustomMetadataProvider();
    }
}

我设置了一个断点,上面的注册正在执行,并且正在设置Current

问题/疑问

永远不会调用CreateMetadata方法。我还需要做什么?

1 个答案:

答案 0 :(得分:3)

您在Global.asax.cs文件中设置了错误的属性。而不是:

System.Web.ModelBinding.ModelMetadataProviders.Current = 
        new CustomMetadataProvider();

应该是这样的:

ModelMetadataProviders.Current = 
        new CustomMetadataProvider();

如果您真的想要提供完整的限定符,那么实际上是:

System.Web.Mvc.ModelMetadataProviders.Current = 
        new CustomMetadataProvider();