asp.net-core-mvcsession-stateasp.net-core-mvc-2.0asp.net-session

Why am I not able to use session storage to store emails? (working on ASP.NET Core MVC)


I am trying to set the session string in the below action controller. Where I set the email.

[HttpPost]
public IActionResult LoginFunc(Login model)
{
    try
    {
        bool employeeIdExists = _DAL.EmployeeIdExists(model.RMEmployeeId);

        if (!employeeIdExists)
        {
            ViewBag.ErrEmployeeDoesntExists = "This Employee Id doesn't exist.";
            return View("~/Views/Home/Login.cshtml");
        }
        else
        {
            _employeeEmailId = _DAL.GetEmailByEmployeeId(model.RMEmployeeId);
            string otp = GenerateOtp(6);

            //TempData["EmployeeEmailId"] = employeeEmailId;
            //TempData["Otp"] = otp;

            //HttpContext.Session.SetString("Otp", otp);

            //Using smtp here                    
            Login_DAL.SendOtpByEmail(otp, smtpHost, smtpPort, cMailId, cMailIDPassword, fromEmailId, configuration, _employeeEmailId);

            DateTime expiryDateTime = DateTime.Now.AddMinutes(30);
            _DAL.AddOtpData(_employeeEmailId, otp, expiryDateTime);

            //SendOtpByEmail(employeeEmailId, otp, smtpHost, smtpPort, cMailId, cMailIDPassword, fromEmailId);
            ViewBag.DisplayOtpModal = true;

            HttpContext.Session.SetString("EmployeeEmail", employeeEmailId);

            // return View("~/Views/Home/OtpPage.cshtml");
            return RedirectToAction("VerifyOtpPage");
        }
    }
    catch (Exception ex)
    {
        TempData["errorMessage"] = ex.Message;
        return View("~/Views/Home/Login.cshtml");
    }
}

In the above code, I don't get any error but when my debugger hits the session line, I am redirected to the login page. And my code doesn't run further to display the otp verification page.

I am trying to get the session value in the below code:

[HttpPost]
public IActionResult VerifyOtp(VerifyOtp enteredOtp)
{
    try
    {
        if (string.IsNullOrEmpty(enteredOtp.Otp))
        {
            ModelState.AddModelError("Otp", "Please enter the Otp.");
            return View("~/Views/Home/OtpPage.cshtml");
        }

        string employeeEmailId = HttpContext.Session.GetString("EmployeeEmail");
                
        bool verifiedOtp = _DAL.VerifyOtp(enteredOtp.Otp, employeeEmailId);

        if (verifiedOtp)
        {
            // return View("~/Views/Home/HomeIndex.cshtml");
            return RedirectToAction("HomeIndex", "Home");
            // return View();
        }
        else
        {
            ViewBag.DisplayOtpModal = true;
            ViewBag.IncorrectOtp = "Invalid or expired OTP.";

            return View("~/Views/Home/OtpPage.cshtml");
        }
    }
    catch (Exception ex)
    {
        TempData["errorMessage"] = ex.Message;
        return View("~/Views/Home/OtpPage.cshtml");
    }
}

And here is my startup.cs file:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.AspNetCore.Http;

namespace WebApplicationFinal
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // Configure your services here

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Configure your middleware here

            app.UseRouting();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSession(); // This should be placed after UseRouting and before UseEndpoints

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=MainPageView}");
            });
        }
    }
} 

Solution

  • I was using the asp.net core 5 approach while I was working in asp.net core 6. In .net 6 there is no startup.cs file and the configurations are written in the program.cs file.