Custom MVC3 Output File

I would like to use caching in my application, but the returned data is specific to the registered user. I cannot use any caching rules in the box when I need to vary by user.

Can someone point me in the right direction to create a custom cache attribute. From the controller, I can access the user from Thread.CurrentPrincipal.Identity;or to the private member of the controller, which is initialized in the controller’s constructor_user

Thank.

+5
source share
3 answers

You can use VaryByCustom. In Global.asax, override the method GetVaryByCustomString:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg == "IsLoggedIn")
    {
         if (context.Request.Cookies["anon"] != null)
         {
              if (context.Request.Cookies["anon"].Value == "false")
              {
                   return "auth";
              }
              else
              {
                   return "anon";
              }
          }
          else
          {
             return "anon";
          }
    }
    else
    {
        return base.GetVaryByCustomString(context, arg);
    }
}

OutputCache:

[OutputCache(CacheProfile = "MyProfile")]
public ActionResult Index()
{
   return View();
}

web.config:

<caching> 
    <outputcachesettings>             
        <outputcacheprofiles> 
            <clear /> 
            <add varybycustom="IsLoggedIn" varybyparam="*" duration="86400" name="MyProfile" /> 
        </outputcacheprofiles> 
    </outputcachesettings> 
</caching>
+9

, . , , , .

:

- ASP.NET MVC , ?

+1

You must use the OutputCache.VaryByCustom Property to specify an arbitrary string variable. And to use it, you must override the method in your Global.asax file

public override string GetVaryByCustomString(HttpContext context, string arg) 
{ 
  if(arg.ToLower() == "currentuser") 
  { 
    //return UserName;
  } 
  return base.GetVaryByCustomString(context, arg); 
}
0
source

All Articles