Asp.net mvc 4 OutputCache因使用会话中的ModelBinder传递的复杂对象属性而异

Asp.net mvc 4 OutputCache因使用会话中的ModelBinder传递的复杂对象属性而异,asp.net-mvc-4,asp.net-caching,Asp.net Mvc 4,Asp.net Caching,我们将Couchbase用于会话和OutputCache 在这种情况下,我们如何通过使用从会话检索值的自定义模型绑定器传递给方法的复杂对象进行缓存 这是我要使用OutputCache属性缓存的方法的签名: [HttpGet] [OutputCache(CacheProfile = "MyObjectsCache", VaryByParam = "myParam")] public ActionResult Index([ModelBinder(typeof (CustomVariableSess

我们将Couchbase用于会话和OutputCache

在这种情况下,我们如何通过使用从会话检索值的自定义模型绑定器传递给方法的复杂对象进行缓存

这是我要使用
OutputCache
属性缓存的方法的签名:

[HttpGet]
[OutputCache(CacheProfile = "MyObjectsCache", VaryByParam = "myParam")]
public ActionResult Index([ModelBinder(typeof (CustomVariableSessionModelBinder<MyClass>))] MyClass myParam)
{
以下是从会话检索对象的方式:

var sessionKey = typeof (MyNamespace.MyClass).FullName;
var httpContext = HttpContext.Current;
MyNamespace.MyClass newObject = null;

if (httpContext.Session != null)
{
    newObject = httpContext.Session[sessionKey] as MyNamespace.MyClass;
}

您是否可以在这个场景中使用
VaryByParam
,或者我必须使用
VaryByCustom

我还没有测试过这个,但它应该可以工作。无论如何,这几乎是你唯一的选择

除了内置的变化方式外,您还可以根据“自定义”进行变化。这将调用Global.asax中的方法,您需要重写:
GetVaryByCustomString
。对于这里的情况,重要的是,此方法是通过
HttpContext
传递的,因此您应该能够查看会话。从本质上讲,解决方案类似于:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    var args = custom.ToLower().Split(';');
    var sb = new StringBuilder();

    foreach (var arg in args)
    {
        switch (arg)
        {
            case "session":
                var obj = // get your object from session
                // now create some unique string to append
                sb.AppendFormat("Session{0}", obj.Id);
        }
    }

    return sb.ToString();
}
这是为处理多种不同类型的“自定义”类型而设计的。例如,如果您想按“用户”进行更改(这很常见),您只需在交换机中添加一个案例即可。重要的一点是,此方法返回的字符串实际上是输出缓存的变量,因此您希望它在这种情况下是唯一的。这就是为什么我在这里用“Session”作为对象id的前缀。例如,如果您刚刚添加了id,比如说
123
,然后在另一个场景中,您根据用户进行了更改,该字符串仅由用户的id组成,该id恰好也是
123
。输出缓存中的字符串应该是相同的,最后会出现一些奇怪的结果。请注意自定义字符串的外观

现在,您只需更改
OutputCache
属性,如下所示:

[OutputCache(CacheProfile = "MyObjectsCache", VaryByParam = "myParam", VaryByCustom = "Session")]

注意:若要同时根据多个自定义内容进行更改,请使用
将它们分开(基于上述代码的工作方式)。例如:
VaryByCustom=“Session;User”

会话在Global.asax.cs中不可用
[OutputCache(CacheProfile = "MyObjectsCache", VaryByParam = "myParam", VaryByCustom = "Session")]