How to Use Session in .NET Core?
Hello, in this article we will look at how we can use session with .net core.
If you, like me, have spent a lot of time with the .net framework for a long time, and a session is a must.
So let’s see how to implement Session in Net Core
To use Session in .Net Core, we first need to go to Startup.cs and find the ConfigureServices Method.
We can say that this method is the area where we specify the technologies to be used while the project is running, let’s use Razor Pages, whether it’s Anti Forgery, I will use it in Session, etc. In this scenario, we will add Session.
For the adding process, we call the AddSession method from the IServiceCollection, which is the parameter, by giving options.
You can name the cookie that .Net Core will hold the session id, you can give an idletimeout with TimeSpan. I gave an absurd number because I don’t want it to drop easily in this project.
Now we can use Session in our projects.
public void ConfigureServices(IServiceCollection services) {
services.AddRazorPages();
services.AddSession(options => {
options.Cookie.Name = ".MySessionName.Session";
options.IdleTimeout = TimeSpan.FromSeconds(987654321);
options.Cookie.IsEssential = true;
});
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
How to set and get Session in .NET Core?
Usage is slightly different.
While creating the session, we need to specify its type, obviously, this allows us to use the session more controlled.
For example, if you are going to keep the UserID as an int.
HttpContext.Session.SetInt32("UserID", person.id);
It is set as above. There are 3 set methods in total. Set, SetInt32, and SetString. We can also access the data when we call the same methods Get Instead of Set.
int UID = (int)HttpContext.Session.GetInt32("UserID");
What you should pay attention to here is that the return may be an empty int. In other words, in case of the possibility of making a request before the session occurs, usages such as pure cast: (int) may cause errors, I wanted to show the simple usage as an example.
You can simply use Session in .Net Core like this, Thanks for reading, I would appreciate it if you could comment.