Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.Cookies: How to append with expiration?

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?

like image 838
g.pickardou Avatar asked Oct 21 '25 04:10

g.pickardou


1 Answers

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.

like image 80
Kirk Larkin Avatar answered Oct 22 '25 20:10

Kirk Larkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!