How to use Session In Asp.net Core
going to show you how to use session in dot net core MVC application
Add below reference
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
Settings to use Session in asp.net core -
Open startup.cs class
Add below line in ConfigureServices section
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
Add below line in Configure section
app.UseSession();
Note - If you will not add these values then you will get below error
System.InvalidOperationException: 'Session has not been configured for this application or request.'
First Method
Set Value in session Variables
In Home Controller Index Method set Session Data As-
public IActionResult Index()
{
HttpContext.Session.SetString("UserInfostatic", "Shashi");
return View();
}
Add another Controller And write below code to get session data
public IActionResult Index()
{
var userInfostatic = (HttpContext.Session.GetString("UserInfostatic"));
if(userInfostatic != null)
{
ViewBag.sessiondata = userInfostatic;
}
return View();
}
Second Method
Set and Receive/Get session Data in Class Variable As -
Add class in Model and set value in model class variable As-
public class UserInfoBO
{
public int Id { get; set; }
public string Email { get; set; }
public string Cust_Name { get; set; }
public string UserType { get; set; }
public UserInfoBO LoadUserData()
{
var userdtl =
new UserInfoBO()
{
Id = 1,
Email = "abc@gmail.com",
UserType = "Admin",
Cust_Name = "Shashi"
};
return userdtl;
}
}
Here in LoadUserData() I have set value statically you can set value here from database also As-
public UserInfoBO LoadUserData(string userName)
{
MVCTestDBContext _db = new MVCTestDBContext();
var userdtl = _db.Login.Where(s => s.Email.Contains(userName)).Select(s =>
new UserInfoBO()
{
Id = s.Id,
Email = s.Email,
UserType = s.UserType,
Cust_Name = s.CustName,
});
return userdtl.FirstOrDefault();
}
Now set above Class data in session –
Go to Home Controller Index Method and write below code –
public IActionResult Index()
{
UserInfoBO userInfo = uf.LoadUserData();
if(userInfo!=null)
{
HttpContext.Session.SetString("UserInfo", JsonConvert.SerializeObject(userInfo));
}
return View();
}
Add another Controller And write below code to get session data
public IActionResult Index()
{
var uf = HttpContext.Session.GetString("UserInfo");
if (uf != null)
{
var userInfo = JsonConvert.DeserializeObject<UserInfoBO>(HttpContext.Session.GetString("UserInfo"));
ViewBag.usertype = userInfo.UserType;
}
Return View();
}