[SOLVED]How to use cookies in .NET Core 3.1 MVC?
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/486
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 13:45:27