jscarle
jscarle

Reputation: 1305

Creating a custom cookie with a custom name in ASP.NET Core 3.1

In ASP.NET Framework, it was possible to define a custom cookie with a custom name in the constructor, like this:

HttpCookie customCookie = new HttpCookie("name");
customCookie.Expires = DateTime.Now.AddMinutes(10);
customCookie["key"] = "value";
context.Response.Cookies.Add(customCookie);

In ASP.NET Core, the approach has changed to something more like this:

CookieOptions cookieOptions = new CookieOptions();
cookieOptions.Expires = DateTime.Now.AddMinutes(10);
context.Response.Cookies.Append("key", "value", cookieOptions);

There seems to be no way to set the "name" of the cookie as there is no option defined in the CookieOptions class.

Upvotes: 2

Views: 3859

Answers (1)

Martin Staufcik
Martin Staufcik

Reputation: 9490

ASP.NET - multi-value cookies compatibility

The line

customCookie["key"] = "value";

is a shortcut to the Values property. It is equivalent to

customCookie.Values["key"] = "value";

This property allows the use of multi-value cookies and is provided for compatibility with previous versions of Active Server Pages (ASP).

ASP.NET Core cookie - no built in compatibility for multi-value cookies

ASP.NET Core removed the support for the old legacy multi-value cookies because this feature was never standardized. More information why it is not supported is here. The link also has a nice extention for multi-value cookies in ASP.NET Core.

This line

context.Response.Cookies.Append("key", "value", cookieOptions);

adds a cookie to the HTTP response and sets the name of the new cookie to "key" and its value to "value".

Upvotes: 4

Related Questions