Hi rani,
You need to add the session service in Startup.cs file in ConfigureServices function.
Then add app.Usersession() inside the configure function.
Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Namespaces
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
// Set Session.
HttpContext.Session.SetString("Name", "Dharmendra");
HttpContext.Session.SetInt32("Age", 30);
// Get value from Session.
string name = HttpContext.Session.GetString("Name");
int? age = HttpContext.Session.GetInt32("Age");
ViewBag.Message = "Name : " + name + "<br />Age : " + age;
return View();
}
}
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Html.Raw(@ViewBag.Message)
</body>
</html>
Screenshot