Is it possible to output cache controller actions differently based on user role? or if they are authenticated or not?
Asked
Active
Viewed 4,097 times
2 Answers
7
Take a look at VaryByCustom.
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.getvarybycustomstring.aspx

Paul Hiles
- 9,558
- 7
- 51
- 76
-
1Thanks, that got me to this, which is working perfect: http://codebetter.com/blogs/darrell.norton/archive/2004/05/04/12724.aspx – Slee Feb 18 '10 at 16:00
4
[Careful: This answer was valid as of 2011]
We add the OutputCache directive like this:
<%@ OutputCache Duration="60" VaryByParam="None" VaryByCustom="SessionID" %>
In MVC, add this attribute to your action
[OutputCache(Duration = 60, VaryByParam="None", VaryByCustom="SessionID")]
Then, in the Global.asax file
Public override string GetVaryByCustomString(HttpContext context, string arg)
{
if(arg.ToLower() == "sessionid")
{
HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionID"];
if(cookie != null)
return cookie.Value;
}
return base.GetVaryByCustomString(context, arg);
}

Jalal El-Shaer
- 14,502
- 8
- 45
- 51
-
3You can get the session cookie name using the [SessionStateSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.sessionstatesection(v=vs.110).aspx) (so that you avoid hardcoding the default cookie name). Also, you should do a case insensitive comparison on the argument, it just looks better. You can check my version of this in this blog post: http://blog.danielcorreia.net/asp-net-mvc-vary-by-current-user/ – Daniel Correia Jul 19 '14 at 20:47