Using the following code in ASP.NET Core 3.1 web application:
var cookies = _contextAccessor.HttpContext?.Response?.Cookies;
if (cookies != null && !_contextAccessor.HttpContext.Response.HasStarted)
{
cookies.Append(key, data);
}
Question
How to add cookie with expiration? IResponseCookies interface (and the internal underlying implementation ResponseCookies) lacks of such an Append overload. Is this intentional, to move in direction to LocalStorage?
Use the overload that takes an instance of CookieOptions:
cookies.Append(
key,
data,
new CookieOptions { MaxAge = TimeSpan.FromDays(1) });
This example sets the MaxAge property, but there's also the Expires property. See this for more about the difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With