Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ProximaB/c71fbfcb770e0c1a0404715972581253 to your computer and use it in GitHub Desktop.
Save ProximaB/c71fbfcb770e0c1a0404715972581253 to your computer and use it in GitHub Desktop.

1. Sessions State

Consisting of a dictionary or hash table on the server, session persist data across requests from a browser.
The sessoin data is backed by a cache. ASP.NET Core maintains session state by giing the client cookie that contains the session ID, which is sent to the server with each request. Session state is ideal for storing user data that's specific to a particular session but doesn't need to be persisted permanently. The server doesn't know when the browser is closed or when the session cookie is deleted. You can either set the session timeout or use the default value of 20 minutes. Data is deleted from the backing store either when you call Session.Clear or when the session expires in the data store.

2. TempData, temp Cookie

ASP.NET Core MVC exposes the TempData property on a controller. This property stores data until it's read. The Keep and Peek methods can be used to
examine the data without deletion. TempData is particularly useful for redirection, when data is needed for more than a single request.
TempData is implemented by TempData providers, for example, using either cookies or session state. Configure TempData:

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

      services.AddSession();
  }

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

3. Query strings

You can pass a limited amount of data from one request to another by adding it to the new request’s query string.
This is useful for capturing state in a persistent manner that allows links with embedded state to be shared through email or social networks.

4. Cookies

Cookies provide a way to store user-specific data in web applications. Because cookies are sent with every request, their size should be kept to a minimum.
Ideally, only an identifier should be stored in a cookie with the actual data stored on the server.
Most browsers restrict cookies to 4096 bytes. In addition, only a limited number of cookies are available for each domain.

5. HttpContext.Items

The Items collection is a good location to store data that's needed only while processing one particular request.

6. Cache

Caching is an efficient way to store and retrieve data. You can control the lifetime of cached items based on time and other considerations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment