Ajapa Gayatri : The Yogic Wish-Fulfilling Tree — Rediscover the sacred rhythm of your breath. Cultivate inner silence that brings clarity, balance, and resilience in daily life.


Use Cookies and Session To Store TempData In ASP.NET Core

If you ever used TempData in ASP.NET MVC, you are probably aware that by default TempData is stored in Session state. This means the web application must have sessions enabled. Luckily, ASP.NET Core 2.0 provides two TempData providers - Cookie based and Session State based. To that end this article shows how to use both of them in an ASP.NET Core application.

If you are unfamiliar with TempData dictionary consider reading this and this first.

Cookie based TempData

By default, ASP.NET Core 2.0 uses cookies based TempData provider. This means TempData values are stored in cookies on the client machine. Since TempData is stored in cookies you don't need Session state enabled through the session state middleware. Storing TempData in cookies can be useful when :

  • The data being stored in TempData is small in size.
  • Web application is part of web farm and you don't want sticky sessions.

Since cookie based TempData is used by default you don't need to do any configuration to use it. Just store and retrieve TempData key-value pairs as you normally do. An example follows :

public IActionResult Index1()
{
    TempData["message"] = DateTime.Now;
    return View();
}


public IActionResult Index2()
{
    return View();
}

The above code shows two actions - Index1 and Index2 - of HomeController. The Index1() action stores a date-time stamp in TempData dictionary with a key name of message. The Index1 view simply offers a hyperlink to navigate to Home/Index2. The Index2() action returns Index2 view. The Index2 view reads TempData and shows the value of message to the user.

Index1 view is shown below :

<h1>Index 1</h1>

@if (TempData.Peek("message") == null)
{
    <h2>TempData has not been set.</h2>
}
else
{
    <h2>TempData has been set.</h2>
}

<br />

<a asp-controller="home" asp-action="index2">
Go to Index2
</a>

As you can see, the Razor code checks whether message has been stored in TempData or not. It does so using the Peek() method of TempData. Since we use Peek() the key won't be removed from TempData. Accordingly a message is displayed in the browser informing the status of message key.

An anchor tag helper renders a hyperlink that points to the Index2() action of HomeController.

The following figure shows a sample successful run of this view :

When user clicks on the hyperlink rendered by Index1. The value of message is outputted in the browser. Markup of Index2 is shown below.

<h1>Index 2</h1>

<h2>@TempData["message"]</h2>

<br />

<a asp-controller="home" asp-action="index1">
Go to Index1
</a>

Index2 simply reads the TempData dictionary and outputs the date-time stamp value in the browser. A hyperlink allows the user to go back to Index1. The following figure shows a sample run of Index2.

How do we know that TempData is really using cookies. Run the application with F12 tools and locate the cookies option. The following figure (FireFox) shows the cookie used by TempData for storing the values.

The cookie value is Base64 encoded. As you might have guessed, since a cookies are being used to store TempData all the limitations of cookie storage apply (browser support, size etc.).

Let's now see how to use Session State based TempData instead of cookie based.

Session state based TempData

To enable Session state based TempData storage you need to enable sessions using middleware and you also need to change the default provider. The following code shows how :

public void ConfigureServices(IServiceCollection
services)
{
    services.AddMvc().AddSessionStateTempDataProvider();
    services.AddSession();
}

public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
    app.UseSession();
    app.UseMvcWithDefaultRoute();
}

The  ConfigureServices() calls AddSessionStateTempDataProvider() to switch the default TempData provider to SessionStateTempDataProvider. It also calls AddSession() to enable in-memory session state for the application. The Configure() calls UseSession() to use the session state middleware.

The  HomeController and its actions - Index1() and Index2() - remain unchanged. If you run the application the final outcome will be the same as before. This time, however, there won't be CookieTempDataProvider cookie. Instead, you will have Session cookie as shown below :

Session state based TempData can come handy when your application is already using session state for other purposes. Also, if you intend to store bigger chunks of data in TempData cookie based storage might not serve the purpose and you may want to switch to session based TempData. To read more about TempData and TempData providers go here.

That's it for now ! Keep coding !!


Author : Bipin Joshi
Bipin Joshi is an independent software consultant and trainer, specializing in Microsoft web development technologies. Having embraced the yogic way of life, he also mentors select individuals in Ajapa Gayatri and allied meditative practices. Blending the disciplines of code and consciousness, he has been meditating, programming, writing, and teaching for over 30 years. As a prolific author, he shares his insights on both software development and yogic wisdom through his websites.

Posted On : 01 January 2018