
How can i use session in a controller class in asp.net?


Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jayraj ChhayaRank #304 · 8.2K reputationPosted May 8, 2024, 6:34 AM EDT
You can access and utilize session variables within a controller class by leveraging the
Sessionproperty provided by theControllerbase class. This property allows you to store and retrieve session data easily.public class HomeController : Controller { public IActionResult Index() { // Storing data in session HttpContext.Session.SetString("UserName", "JohnDoe"); // Retrieving data from session var userName = HttpContext.Session.GetString("UserName"); return View(); } }Jaya PrakashRank #1,293 · 1.3K reputationPosted May 8, 2024, 7:20 AM EDT
Jayraj Chhaya not working bro im using only asp.net not core
Jayraj ChhayaRank #304 · 8.2K reputationPosted May 8, 2024, 7:36 AM EDT
Hi Jaya Prakash,
Please share error details or screen shot so I can help
Jaydeep PatilRank #205 · 11.7K reputationPosted May 8, 2024, 12:01 PM EDT
Steps:
1. Configure session in startup class services and middleware section
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); // Session timeout options.Cookie.HttpOnly = true; // Cookie accessible only on the server side options.Cookie.IsEssential = true; // Make the session cookie essential }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseSession(); // Enable session middleware app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }2. Access inside the controller
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; public class MyController : Controller { public IActionResult Index() { // Store data in session HttpContext.Session.SetString("UserName", "JohnDoe"); return View(); } public IActionResult GetUserName() { // Retrieve data from session string userName = HttpContext.Session.GetString("UserName"); if (userName != null) { return Content("User Name: " + userName); } else { return Content("User Name not found in session."); } } public IActionResult ClearSession() { // Remove specific item from session HttpContext.Session.Remove("UserName"); // Or clear entire session // HttpContext.Session.Clear(); return Content("Session data cleared."); } }Jignesh KumarRank #91 · 22.9K reputationPosted May 8, 2024, 1:07 PM EDT
Hello Jaya Prakash,
Please refer to this thread which has a very good explanation of the mvc core application,
you need to install the Nuget package for the session "Microsoft.AspNetCore.Session package",
https://www.c-sharpcorner.com/blogs/session-management-in-asp-net-core-mvc
public class HomeController : Controller { public IActionResult Index() { string MySessionValue = "Jaya Prakash"; HttpContext.Session.SetString("SessionKeyName", MySessionValue); } } // Access in another Controller public class TestSessionController : Controller { public IActionResult Index() { var nameFromSession = HttpContext.Session.GetString(SessionKeyName); } }Jaya PrakashRank #1,293 · 1.3K reputationPosted May 9, 2024, 3:33 AM EDT
Jayraj Chhaya
Actually i take web api controller in my asp.net project i just want to store that otp in session how
when i keep [EnableSessionState] getting assembly reference error could not be found
public class RentPayAPIsController : ApiController { [HttpPost] [Route("api/RentPayAP/RegterRemitter")] [ActionName("RegterRemitter")] public HttpResponseMessage RegterRemitter([FromBody] Beneficries oMBLoginRequest) { oMBErrorResponse.OTP = dtremitterotp.Rows[0]["OTP"].ToString(); } }Jaimin ShethiyaRank #177 · 13.7K reputationPosted May 8, 2024, 11:51 AM EDT
Hello,
Please refer the below links,
In this link use the session in the API controller side.
https://www.researchgate.net/publication/371904967_Https_Session_Authentication_in_aspnet_Core_Web_API
Here is the link for, asp.net core mvc
https://dotnettutorials.net/lesson/sessions-in-asp-net-core-mvc/
Thanks