EKsumic's Blog

The current theme of this website is Japanese learning.

Click the left button to use the catalog.

OR

[SOLVED]How to use cookies in .NET Core 3.1 MVC?

You only need to write these 3 methods in the controller. (Note that it must be written in the controller)

protected string GetCookies(string key)
{
    HttpContext.Request.Cookies.TryGetValue(key, out string value);
    if (string.IsNullOrEmpty(value))
        value = string.Empty;
    return value;
}
public void SetCookies(string key, string value, int days = 30)
{
    HttpContext.Response.Cookies.Append(key, value, new CookieOptions
    {
        Expires = DateTime.Now.AddDays(days)
    });
}
protected void DeleteCookies(string key)
{
    HttpContext.Response.Cookies.Delete(key);
}

I dare not say that this is the best way, but I want to say that it is effective.

This article was last edited at 2020-10-24 22:45:27

* *