TempData not cleared between requests when using ContainsKey

T

Recently I was trying to add a simple message to the top of the screen if the user had been logged out.

This message, should appear only once. If the user navigates away from the page, it shouldn’t show again.

So, it made sense to use TempData

In my controller, I had something like this:

_authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

TempData["LoggedOut"] = "True";
return RedirectToAction("Index", "Home", new { area = "" });

Then, in my view, a simple check:

@if (TempData.ContainsKey("LoggedOut"))
{
    <div class="alert alert-info" role="alert">
        You have been logged out.
    </div>
}

The issue is here, using ContainsKey doesn’t mark the item for deletion. So on page reload, the TempData dictionary still contains that key, so the message is still displayed.

The solution is to change the ‘if’ statement to

if (TempData["LoggedOut"] != null)

Reading (by accessing the dictionary item by index) marks the item for deletion on the next request.