Cookies in .Net Core

Asked 1 year 6 months 23 days 10 hours 18 minutes ago, Viewed 295 times

Cookie is a smaller piece of information stored on a computer, usually as a text file. It keeps the information about you and your activities, like your preferred language or country. Cookies can also help web developers track user behaviour to improve our services and web sites.

VisitorsController.cs
private IHttpContextAccessor _accessor;

public VisitorsController(IHttpContextAccessor accessor)
  {
     _accessor = accessor;
     //Other code
  }
Set cookie.
public void setCookie()
 {
     CookieOptions options = new CookieOptions();
     options.Expires = DateTime.Now.AddDays(7);
     _accessor.HttpContext.Response.Cookies.Append("name", "value", options);
 }
Read cookie.
public void readCookie()
 {
     var name = _accessor.HttpContext.Request.Cookies["name"];
 }
Remove cookie.
public void removeCookie()
 {
     _accessor.HttpContext.Response.Cookies.Delete("name");
 }

Cookies implementation:

Startup.cs
public void ConfigureServices(IServiceCollection services)
  {
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     //Other code
  }