c# - VaryByCustom 和模型绑定(bind)

标签 c# asp.net-mvc model-binding outputcache

我有一个模型绑定(bind)类,我想对其使用输出缓存。我找不到在 GetVaryByCustomString

中访问绑定(bind)对象的方法

例如:

public class MyClass
{
    public string Id { get; set; }
    ... More properties here
}

public class MyClassModelBinder : DefaultModelBinder
{
   public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
      var model = new MyClass();
      ... build the class       
      return model;
    }
}

我在 Global.cs 中设置了 Binder

ModelBinders.Binders.Add(typeof(MyClass), new MyClassModelBinder());

然后像这样使用输出缓存。

[OutputCache(Duration = 300, VaryByCustom = "myClass")]
public ActionResult MyAction(MyClass myClass)
{
   .......

public override string GetVaryByCustomString(HttpContext context, string custom)
{
   ... check we're working with 'MyClass'

   var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
   var myClass = (MyClass)routeData.Values["myClass"]; <-- This is always null

虽然模型绑定(bind)程序已触发,但 myClass 不在路由表事件中。

一如既往地欢迎任何帮助。

干杯

最佳答案

模型绑定(bind)器不会将模型添加到 RouteData,因此您不能指望从那里获取它。

一种可能性是将模型存储在自定义模型 Binder 中的 HttpContext 中:

public class MyClassModelBinder : DefaultModelBinder
{
   public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
      var model = new MyClass();
      // ... build the class

      // Store the model inside the HttpContext so that it is accessible later
      controllerContext.HttpContext.Items["model"] = model;
      return model;
    }
}

然后使用相同的键(在我的示例中为 model)在 GetVaryByCustomString 方法中检索它:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    var myClass = (MyClass)context.Items["model"];

    ...
}

关于c# - VaryByCustom 和模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196701/

相关文章:

c# - 在正文中使用 int/string (简单类型)发布到 asp.net core web api 2.1 不起作用

c# - 使用 EntityFramework 和 MVC ModelBinding 保存具有特殊字符的字段时出错

c# - 检查通用类型的字段

c# - 在 Windows 应用程序中使用 FolderBrowserDialog 浏览多个文件夹

c# - 在 Selenium Webdriver [C#] 中选择单选按钮

javascript - 如何将 Javascript 字典传递给 Controller ​​,其中 C# 字典值是一个对象

c# - 如何模拟 HttpContext.User

javascript - 为什么在 ASP.NET MVC 中我得到 JSON 而不是 FileDownload?

c# - MVC5 模型绑定(bind)——子对象全部为 null

c# - JSON stringify 到 C# Webservice