Cookies in .Net Core
Asked 1 year 7 months 11 days 20 hours 57 minutes ago, Viewed 305 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.csprivate 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.cspublic void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//Other code
}
Like
1