Post

Cookie and Session for ASP.net MVC app

  • cookies : key/value pare that’s created on the server and passed to the user’s browser in an HTTP response. Then, the browser passes the cookie back to the server with each subsequent HTTP request.
  • session state : the data for a user session is stored in key/value paris on the server. This data persists across all the HTTP requests that a user makes until the app removes the data or the session ends.

  • State refers to the current status of the properties, variables, and other data maintained by an app for a single user.
  • HTTP is a stateless protocol. That means that it doesn’t keep track of state between round trips. Once a browser makes a request and receives a response, the app terminates and its state is lost.
  • ASP.NET Core MVC provides several ways to maintain the state of a web app.
  • A cookie is a key/value pair passed to the user in an HTTP response and passed

    back to the server with each subsequent HTTP request.

  • Session state works by having the server store the session data for a user and by using a cookie to associate the user’s web browser with the correct session data.

How to configure an app to use session state.

  1. add some statements in program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// to configure an app to use session state. 
builder.Services.AddMemoryCache();
builder.Services.AddSession(options =>
{
    // change idle timeout to 5 minutes - default is 20 minutes
    options.IdleTimeout = TimeSpan.FromSeconds(60 * 5);
    options.Cookie.HttpOnly = false;     // default is true
    options.Cookie.IsEssential = true;   // default is false
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

The example is to add session state to the services for the app. To do that, it calls the AddMemoryCache() and AddSession() methods that are available from the services parameter. When you call these methods, you must call them before you call the AddControllersWithViews() method.

1
2
3
4
5
6
// identifies the service to use for session state.
app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

This code identifies the service to use for session state. To do that, it calls the UseSession() method from the app parameter. For this to work, you must call this method before you call the UseEndpoints() method.

How to work with session state items in a controller

  • Method of the ISession interface that set, get and remove items. SetInt32(key, value) : Stores the int value in the session object and associates it with the specified key. SetString(key, value) : Stores the string value in the session object and associates it with the specified key. GetInt32(key) : Returns the int value associated with the specified key, or null if there’s no value. GetString(key) : Returns the string value associated with the specified key, or null if there’s no value. Remove(key) : Removes the value associated with the specified key if the key is found.

  • A using directive for session state in a controller

1
using Mircrosoft.AspNetCore.Http;
  • An action method that gets and sets a session state value

The GetInt32 method returns a nullable integer (int?), which means it could be null if the session value doesn’t exist. So, before using it, you should check if it has a value. You can do this using the null-conditional operator (?.) or by explicitly checking for null.

1
2
3
4
5
6
7
8
9
public IActionResult Index()
{
    int num = HttpContext.Session.GetInt32("num") ?? 0;
    num += 1;
    HttpContext.Session.SetInt32("num", num);
    return View();
}
// doesn’t pass the int value to the view. 
// That’s because the view can retrieve the int value from session state
  • A using directive for session state in a view
1
2
// To enable all of the featuers of its Session property
@using Microsoft.AspNetCore.Http
  • A Razor code block that gets a session state value
1
2
3
@{
	int num = Context.Session.GetInt32("num");
}
  • A Razor expression that gets a session state value
1
<div>@Context.Session.GetInt32("num")</div>

How to work with cookies

A cookie is a key/value pair that’s stored in the user’s browser or on the user’s disk. A web app sends a cookie to a browser via an HTTP response. Then, each time the browser sends an HTTP request to the server, it sends that cookie back.

A session cookie is stored in the browser’s memory and exists only for the duration of the browser session. A persistent cookie, on the other hand, is stored on the user’s disk and is retained until the cookie’s expiration date, or until the user clears the cookie.

How to work with session cookies

  • Two properties of the Controller class Request : Represents the HTTP reqeust sent from the browser to the server Response : Represents the HTTP response sent from the server to the browser

  • Code that sets a session cookie

1
Response.Cookies.Append("username", "Grace");
  • Code that deletes a cookie
1
Response.Cookies.Delete("username");
  • Code that gets a cookie
1
string value = Request.Cookies["username"]; // brackets, not parentheses
  • Some of the properties of the CookieOptions class Domain : The domain to associate the cookie with. The default value is null. Expires : The cookie’s expiration date and time. The default value is null. Path : The cookie’s path. The default path is “p’. MaxAge : The maximum age for the cookie. The default value is null. SameSite : The value for the cookie’s SameSite attribute. The values can be Lax or Strict. The default value is Lax. Secure : Indicates whether the cookie can be transmitted over HTTPS only. The default value is false.

  • A using directive that’s necessary to work with the CookieOptions class

1
using Microsoft.AspNetCore.Http;
  • Code that sets a persistent cookie
1
2
var options = new CookieOptions { Expires = DateTime.Now.AddDays(30) }; 
Response.Cookies.Append("username", "Grace", options);

Reference. Murach’s ASP.NET CORE MVC, Mary Delamater, Joel Murah

This post is licensed under CC BY 4.0 by the author.