2

I have many create Views in my MVC application. I have cached the GET Index action method using [OutputCache] annotation, so that the view is stored in the cache.

I store the details about the currently logged in user in the Session, and display the user's first name in the layout after reading it from the Session.

The problem is, since I have cached the views, the layout is also cached. So even if a different user logs in, the first name of the previous user is visible, because the layout was cached last time.

Is there any way to prevent caching of the layout? Or is there any other way I can stop the first name display from getting cached?

I thought about using VaryByCustom, but I am not sure what to do in the GetVaryByCustomString method that I will need to override.

What would be the best approach to prevent caching of the layout, or alternately, varying the cache by user?

EDIT:

I must clarify that I am using my own custom user management logic. I have my own Users table in the database and I retrieve relevant data on login and store it in Session.

Bhushan Shah
  • 1,028
  • 8
  • 20

1 Answers1

3

Here's one way you could use the GetVaryByCustom function in Global.asax.

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        var varyString = string.Empty;

        if(context.User.Identity.IsAuthenticated)
        {
            varyString += context.User.Identity.Name;
        }

        return varyString;
    }

What you could also do is get the user information with an ajax request and insert it using javascript, that way you don't need to recache the page for each user. Personally I would go with this approach if the username is the only thing that differs.

JuhaKangas
  • 875
  • 5
  • 17
  • I am not using Membership Provider. I have my own Users table in my database and my own custom logic by which I get user data and store it in `Session` on login. – Bhushan Shah May 08 '14 at 06:00
  • Ok, sure, just apply that to this example instead. You can access the session from the HttpContext that is sent to this function. – JuhaKangas May 08 '14 at 08:19