asp.net - 如何扩展 CachedDataAnnotationsModelMetadataProvider?

标签 asp.net asp.net-mvc asp.net-mvc-4 metadata modelmetadata

我们希望使用 CachedDataAnnotationsModelMetadataProvider照原样improves performance我们在 MVC4 应用程序中使用了大量元数据。

我们目前正在创建一个自定义 ModelMetadataProvider 继承自 DataAnnotationsModelMetadataProvider 并覆盖 CreateMetadata属性进行一些自动显示名称创建,例如从名称等中删除 Id。但是我们也想缓存它,所以我们想将我们的自定义 ModelMetadataProvider 建立在 CachedDataAnnotationsModelMetadataProvider 上。

如果我们尝试覆盖 CreateMetadata我们不能,因为它是密封的。它被密封的任何原因 - 我想我可以获得源代码,只是重新实现只是发现我无法扩展很奇怪?

有没有人做过类似的事情?

最佳答案

我猜它被密封的原因是因为实际 CreateMetadata实现包含您不应修改的缓存逻辑。

延长CachedDataAnnotationsModelMetadataProvider ,我发现以下似乎运作良好:

 using System.Web.Mvc;

 public class MyCustomMetadataProvider : CachedDataAnnotationsModelMetadataProvider
 {
      protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)
      {
           var result = base.CreateMetadataFromPrototype(prototype, modelAccessor);

           //modify the base result with your custom logic, typically adding items from
           //prototype.AdditionalValues, e.g.
           result.AdditionalValues.Add("MyCustomValuesKey", prototype.AdditionalValues["MyCustomValuesKey"]);

           return result;
      }

      protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)
      {
           CachedDataAnnotationsModelMetadata prototype = base.CreateMetadataPrototype(attributes, containerType, modelType, propertyName);

           //Add custom prototype data, e.g.
           prototype.AdditionalValues.Add("MyCustomValuesKey", "MyCustomValuesData");

           return prototype;
      }
 }

关于asp.net - 如何扩展 CachedDataAnnotationsModelMetadataProvider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19199084/

相关文章:

c# - 永远等待本地主机!

jquery - 为什么 Ajax.BeginForm 返回另一个页面中的部分 View

javascript - 在 javascript 中将 C# 数组转换为 json

javascript - AJAX 在 ASP.NET MVC 中加载局部 View - 脚本运行不止一次

c# - 如何使用不同的参数在同一 Controller 中调用不同的 GET 方法?

ASP.NET 编译模式“自动”与“从不”

c# - ASP.NET 日期和时间选择器?

asp.net - 使用内存对 .ToListAsync() 进行单元测试

.net - 在 ASP.NET MVC 中添加对 View 的引用

jquery - 当没有图表时如何禁用打印图表按钮