Using Cookies in Razor Pages

Cookies are small pieces of text that are passed between browser and web server with every request. Cookies are commonly used to store relatively small amounts of data such as user preferences which help the site remember which features to turn on or off, for example. They might be used to record the fact that the current user has authenticated and is allowed to access restricted areas of the site, or that the user has accepted cookies.

The storage duration of a cookie is determined by the type of cookie and the expiry date that it is given. Cookies with no expiry date are not stored on the client machine and are cleared at the end of the user's session (usually when the user closes the browser). Persistent cookies - ones that have an expiry date set are typically stored as text files by the browser on the client machine.

Cookies in Razor Pages are enabled by default.

You create or set a cookie within a PageModel or Razor file like this:

Response.Cookies.Append("MyCookie", "value1");

You can read the value of the cookie as follows:

var cookieValue = Request.Cookies["MyCookie"];

The value returned from reading a non-existent cookie is null:

var cookieValue = Request.Cookies["nonexistent"]; //return null

Cookie options provide access to additional configuration of cookies. The following example specifies an expiry time, making the cookie persistent:

var cookieOptions = new CookieOptions
{
    Expires = DateTime.Now.AddDays(30)
};
Response.Cookies.Append("MyCookie", "value1", cookieOptions);

The full list of properties is as follows:

Property Data Type Description
Domain string The domain(s) that the cookie is accessible to. If it is not specified, the cookie is only sent to the domain of the current document. If provided, all sub-domains are also included.
Expires DateTime The expiry date
HttpOnly bool Specifies whether the cookie is available to client-side code. false(the default) means that the cookie is accessible to JavaScript, which may present a security risk. If set to true, the cookie is only available to code executing on the server.
Path string The relative path that the cookie should be accessible to. If not specified, the cookie is available to all pages in the domain(s). Subdirectories are also included. For example, /account will match /account, /account/client etc.
SameSite SameSiteMode enum Possible values are Lax (default), None, Strict. The SameSite option is intended to help in the prevention of CSRF or cookie hijacking attacks, but it is not supported by all browsers. It therefore should not be relied on.
Secure bool Specifies whether the cookie should only be sent with secure (HTTPS) requests. The default is false, which means that the cookie will be sent on all requests, regardless of protocol.

Cookies are transferred in plain text, so they are not the place for sensitive data unless you take responsibility for encryption and decryption of the content yourself.

Cookies are limited to around 4Kb in size each/per domain (depending on the browser) and are consequently not the place for storing large amounts of data. The Web Storage API is the recommended alternative for this purpose.

Cookies depend on the browser. If the user changes their browser or device, any previously set cookies will not be available. They will also disappear if the user chooses to delete cookies. Non-persistent cookies (those without an expiration date) are removed when the browser application is shut down. If you have an application open in multiple tabs in the same browser, all tabs will share the same cookie. If you close all tabs in which the application is running, but keep the browser window open, the cookie will continue to persist.

Multiple value cookies

Prior to .NET Core, it is possible to store multiple values per cookie in ASP.NET and classic ASP applications. This is not actually how cookies work, and the mechanisms that enable this capability have not been migrated to ASP.NET Core. You are advised to save one value per cookie. If you want to replicate the ability to store and retrieve multiple values, you must implement your own data serialisation/de-serialisation strategy (e.g. JSON), although you are advised to bear cookie size limitations in mind.

Last updated: 05/05/2023 09:41:39

© 2018 - 2024 - Mike Brind.
All rights reserved.
Contact me at Outlook.com