简体   繁体   English

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

[英]Why is Custom DataAnnotationsModelMetadataProvider's CreateMetadata never being called?

I created a custom provider by inheriting the DataAnnotationsModelMetadataProvider and overriding the CreateMetadata method: 我通过继承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
    }
}

Then I registered it in Global.asax within MvcApplication class: 然后我在MvcApplication类中的Global.asax注册了它:

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

I put a breakpoint and the registration above is executing and Current is being set. 我放了一个断点,上面的注册正在执行,并且正在设置Current

Problem/Question 问题/疑问

The CreateMetadata method is never being called. 永远不会调用CreateMetadata方法。 What else do I need to do? 我还需要做什么?

You're setting the wrong property in your Global.asax.cs file. 您在Global.asax.cs文件中设置了错误的属性。 Instead of: 代替:

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

It should just be this: 它应该是这样的:

ModelMetadataProviders.Current = 
        new CustomMetadataProvider();

Which if you really want to provide the full qualifier is actually: 如果你真的想要提供完整的限定符,实际上是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM