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!
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!
Glad it is useful 🙂
It is very helpful to my project that I am working on to migrate a old site to .net core to run on cloud foundry.
Thanks,
Walter
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
Thanks! Didn’t know it was planned for 1.1. Well, if the two are feature equivalent I think there’s no big need in maintaining it. Most people will likely go with the built-in implementation anyway, as it’s one less package. Nevertheless, I’ll probably keep the package up to date with future releases.
I saw you posted on their github page (https://github.com/aspnet/Mvc/issues/5212), maybe they will merge some of your changes with theirs who knows 😛