Welcome to AspAdvice Sign in | Join | Help

VaryByCustom Caching By User

Ran into an interesting bug today with one of my applications.  A user control that provides messages based on a user's account was showing the wrong information to other users in our testing.  The user control was set up with an output cache directive and a VaryByParam="*" setting, yet it was showing other users' messages (one in particular) to basically everybody - not good.  The funny thing was, it was only doing it on one server instance, not on localhost, despite its having the same code and same database.

Well, we quickly figured out that this was a caching issue.  The problem was that everywhere in the application, the account the user is accessing is specified with an ID in the querystring, so the VaryByParam="*" should do the trick.  Everywhere, that is, but one page: the very first page the user encounters and, coincidentally, the one with the problem.

To correct the issue, we (as in Brendan) added a VaryByCustom="userName" attribute to the OutputCache directive, like so:

<%@ OutputCache Duration="99999" VaryByParam="*" VaryByCustom="userName" %>

Then, to make the VaryByCustom work, the final step is to add the following to Global.asax:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg == "userName")
    {
        return context.User.Identity.Name;
    }
    return string.Empty;
}

Published Monday, October 29, 2007 12:00 PM by ssmith
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: VaryByCustom Caching By User

Good to know!

Monday, October 29, 2007 4:04 PM by Andrei Rinea

# re: VaryByCustom Caching By User

Very awesome!  Thanks for this nugget of wisdom.

Wednesday, May 13, 2009 1:27 PM by Stuart B

# re: VaryByCustom Caching By User

Hi Steven,

I i have one user control and i want to use cache on that usercontrol.In user control i have to upload some feeds for that loged user can you suggest me how to make that usercontorl fast acess.

Monday, May 25, 2009 3:39 AM by Prakash

# re: VaryByCustom Caching By User

Perfect - just the example I needed.

Monday, June 15, 2009 6:52 AM by Adam C

# re: VaryByCustom Caching By User

You saved my day with this! :)

Monday, June 22, 2009 7:24 PM by Ted

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below