Using cookies to store session in ASP MVC

前端 未结 6 1537
野性不改
野性不改 2021-02-03 10:28

Storing the entire session in a cookie has been standard in Rails for the last few years - is there an easy way to achieve something similar with ASP MVC?

By default, an

6条回答
  •  悲&欢浪女
    2021-02-03 11:06

    I recommend storing TempData in the cookie (as opposed to the entire session).

    In order to store TempData in the cookie, you need to override ITempDataProvider and implement your own custom provider.

    There is actually a nuget package available (which does this custom implementation for you): BrockAllen.CookieTempData and here is the documentation. The good thing about this package is that it both compress and encrypts your TempData, so you don't need to worry about sending plain text over the Internet.

    All you need to do is to install the nuget package and then override CreateTempDataProvider in your ControllerBase class:

    using BrockAllen.CookieTempData;
    
    namespace myProject.web.Controllers
    {
        public class ControllerBase : Controller
        {
            // use CookieTempDataProvider instead of default provider
            protected override ITempDataProvider CreateTempDataProvider()
            {
                return new CookieTempDataProvider();
            }
        }
    }
    

提交回复
热议问题