Wednesday, February 10, 2016

Scenario where you do not want to use output caching in ASP.NET (MVP/WebAPI)

Always fun to get to the bottom of weird issues when you didn’t write the code yourself.

Take a look at the following method declaration.

[OutputCache(Duration = 3600, VaryByParam = "none", Location = OutputCacheLocation.Any, NoStore = true)]
public async Task<JsonResult> GetCurrentUser()
{
    var userId = UserHelperFunctions.GetCurrentUserId();
    var userName = UserHelperFunctions.GetUserName(userId);
    var hasPrivilege = <check admin access>

This is what happens, User A logs in and retreives user data, and within the next hour, every other visitor will get user A’s information. Also pay attention to line 6

Wow!

There are ways to solve this, for example like in this SO question, but for now I’ll set it to the below to make sure it’s not cached at all.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]