In this article you will learn following things:
- What is Session?
- How many ways for Session storage?
- How to Enable Session in .Net 8 Asp.Net Core MVC Application?
- How to set or store the value in session?
- How to get or retrieve the value of session?
- How to remove particular session key?
- How to remove all session keys?
- Walk-through on session implementation.
What is a Session?
Session is KEY-VALUE structure to store the user specific data. In Asp.Net Core .NET 8 session is not enable by default, we have to enable it. Session data persists across multiple HTTP requests.
How many ways for Session storage?
- In-Memory Cache: Server base storage. Storage capacity is depend upon server’s available memory. Best for single server base environment.
- Distributed Cache: Session storage not on one server its store on multiple server. Distributed cache work with Redis, Sql Server etc. .
How to Enable Session in .Net 8 Asp.Net Core MVC Application?
builder.Services.AddSession();
Add another line just after app declaration line:
app.UseSession();
How to set or store the value in session?
Create or Setting Session value.
Syntax
HttpContext.Session.SetString(KEY,VALUE);
HttpContext.Session.SetInt22(KEY,VALUE);
Example
HttpContext.Session.SetString(“USERNAME”, UserName);
HttpContext.Session.SetString(“USERID”,Convert.ToString(UserID));
How to get or retrieve the value of session?
Getting Session value.
Syntax
HttpContext.Session.GetString(KEY);
HttpContext.Session.GetInt22(KEY);
Example
HttpContext.Session.GetString(“USERNAME”);
HttpContext.Session.GetString(“USERID”);
How to remove particular session key?
You can easily remove a specific session key.
Syntax
HttpContext.Session.Remove(KEY);
Example
HttpContext.Session.Remove(“UESERNAME”);
How to remove all session keys?
You can delete/remove/clear all sessions in one go.
HttpContext.Session.Clear();
Clear: It remove all the current session entries from the server.
OR
HttpContext.SignOutAsync();
SignOutAsync: It end the current user session and remove or clear the user’s authentication cookie from the server.
Walk-through on session implementation
In this article I had used Visual Studio 2022. After follow step by step you are able to implement SESSION in your Asp.Net Core project.






Jignesh KumarPosted Dec 10, 2024, 6:55 PM
Thanks for sharing its informative.