Cookie-based TempData for ASP.NET Core

When developing web applications, it is common to persist some small state across a POST-redirect-GET flow (e.g. feedback message to a user after some action). In ASP.NET, TempData is the appropriate mechanism for this scenario: it persists a value until the next time it is fetched.

The default TempData implementation on ASP.NET MVC 5 and ASP.NET Core MVC is based on session storage. Another approach is to use a cookie as storage, making a client’s TempData flow with him. On ASP.NET MVC 5 I’ve been successfully using Brock Allen’s CookieTempData provider for the last few years. However, it doesn’t support ASP.NET Core.

I’ve implemented a cookie-based TempData provider for ASP.NET Core MVC. The code is available on GitHub and the library is published as a NuGet package. To replace the default provider with the cookie-based one, you just need to add a call to AddCookieTempData on your ConfigureServices method:

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

The cookies are serialized in BSON and protected using the new data protection APIs. Feel free to provide feedback. Hope this helps!

Advertisements

6 thoughts on “Cookie-based TempData for ASP.NET Core

  1. Just before starting to adapt Brock’s implementation to .NET Core, I found your blog post via the Trackbacks of his blog; thanks Luís for saving me some time and headaches!

  2. Hi Luis, nice work there!
    Do you have plans to keep maintaining your repo even after asp.net core 1.1 ships? As it will include their own implementation of cookie tempdata

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s