C# Concepts 6
C# Concepts 6
• Cookies and sessions are mechanisms to store user data and maintain
state between HTTP requests in web applications. In ASP.NET Core,
managing cookies and sessions involves configuring middleware and
using appropriate APIs.
C#: Cookies
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
if (Request.Cookies.TryGetValue("UserName", out
string userName))
{
return Ok($"UserName: {userName}");
}
return NotFound("Cookie not found.");
}
}
Deleting a Cookie: Example – Deleting a Cookie in
ASP.NET Core
using Microsoft.AspNetCore.Mvc;
• Definition: Sessions store user data on the server side and are
identified by a unique session ID, typically stored in a cookie on the
client's browser. Sessions are used to maintain state across multiple
HTTP requests.
Sessions - Characteristics:
• Server-Side Storage: Data is stored on the server, reducing
exposure to client-side manipulation.
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Using Sessions in Controllers -
Example: Setting and Getting
Session Data
using Microsoft.AspNetCore.Mvc;
• Since sessions can only store byte arrays, strings, or integers directly,
to store complex objects, you need to serialize and deserialize them,
typically using JSON.
Example - Storing a Complex Object
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;