Using Cookies in ASP.NET Core apps

cookies

Using Cookies in ASP.NET Core apps

What are cookies

  • Cookies are small data files sent by websites that are stored in the browser
  • Cookies are sent every time a request is sent to the server
  • Cookies are useful for persisting user login, tracking user activity to create personalized experiences, etc.

cookies_arch

Demo

  • We will create a simple TODO list web app using ASP.NET Core
  • The server will save the todo list in the user’s browser using cookies
  • A server can set a cookie and send it in the response to the client’s browser
  • The browser will update the cookie
  • Each cookie has a unique key
  • In our demo application, the server sets a cookie to store todos in the client’s browser using Response.Cookies.Append
Response.Cookies.Append(nameof(Todo), JsonSerializer.Serialize(todos));

  • Client Browser sends cookies to the server in every request
  • The cookie data can be retrieved using Request.Cookies
  • In our demo application, the cookie containg the todos is accessed in the server using
Request.Cookies[nameof(Todo)] 

  • A server cannot delete the client browser cookie
  • But the cookie can be markes as expired which in a way tells the browser to not use the cookie
  • A cookie can be deleted from the server using Response.Cookies.Delete

Comments

Popular posts from this blog

ClaimsPrincipal, ClaimsIdentity, Claims explained in dotnet authentication

Cookie based authentication & authorization in ASP.NET Core explained

Implicit usings, top level statements, file scoped namespaces in dotnet