skip to Main Content

I followed the example of this tutorial (https://www.c-sharpcorner.com/article/simple-login-and-registration-form-in-asp-net-mvc-using-ado-net/) to create a simple registration and login pages for C# MVC .Net Web app.

I was able to implement the user registration to a local mysql hosted by Xampp

However for the UserLoginController I’m getting the following error:

InvalidOperationException: Session has not been configured for this application or request.
Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
Project.UserLoginController.Index(Enroll e) in UserLoginController.cs
+
                    HttpContext.Session.SetString("Email", e.Email);
lambda_method28(Closure , object , object[] )

Below are some of my code and configuration:

Startup.cs (I had to add manually because "dotnet new mvc -o Project did not add it")

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


namespace Project
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Add this line

            // Other service configurations
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Other middleware configurations
            
            app.UseSession();
            
            app.UseRouting();
            
            // Other endpoint and routing configurations
        }

    }
}

UserLoginController.cs

using Microsoft.AspNetCore.Mvc;
using System.Data;
using MySql.Data.MySqlClient;
using Project.Models;
using System.Data.SqlClient;

namespace Project.Controllers
{  
    public class UserLoginController : Controller  
    {   
        // GET: /UserLogin/  
        public string status;  
          
        public ActionResult Index()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Index(Enroll e)
        {
            string connectionString = "Server=localhost;Port=3306;Database=database;Uid=root;Pwd=root;";
            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                string sqlQuery = "SELECT Email, Password FROM Enrollment WHERE Email = @Email AND Password = @Password";
                con.Open();
                MySqlCommand cmd = new MySqlCommand(sqlQuery, con);
                cmd.Parameters.AddWithValue("@Email", e.Email);
                cmd.Parameters.AddWithValue("@Password", e.Password);
                MySqlDataReader reader = cmd.ExecuteReader();
                
                if (reader.Read())
                {
                    HttpContext.Session.SetString("Email", e.Email);
                    return RedirectToAction("Welcome");
                }
                else
                {
                    ViewData["Message"] = "User Login Details Failed!!";
                }

                con.Close();
            }

            return View();
        }

        [HttpGet]
        public ActionResult Welcome()
        {
            Enroll user = new Enroll();
            DataSet ds = new DataSet();

            string connectionString = "Server=localhost;Port=3306;Database=database;Uid=root;Pwd=root;";
            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand("sp_GetEnrollmentDetails", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Email", HttpContext.Session.GetString("Email"));
                    con.Open();
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(ds);
                    List<Enroll> userlist = new List<Enroll>();
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        Enroll uobj = new Enroll();
                        uobj.ID = Convert.ToInt32(row["ID"].ToString());
                        uobj.FirstName = row["FirstName"].ToString();
                        uobj.LastName = row["LastName"].ToString();
                        uobj.Password = row["Password"].ToString();
                        uobj.Email = row["Email"].ToString();
                        uobj.PhoneNumber = row["Phone"].ToString();
                        uobj.SecurityAnswer = row["SecurityAnswer"].ToString();
                        uobj.Gender = row["Gender"].ToString();

                        userlist.Add(uobj);
                    }
                    user.Enrollsinfo = userlist;
                }
                con.Close();
            }

            ViewBag.Email = HttpContext.Session.GetString("Email");

            return View(user);
        }


        public ActionResult Logout()
        {
            HttpContext.Session.Clear();
            return RedirectToAction("Index", "UserLogin");
        }
    }
} 

Index.cshtml

@model Project.Enroll    
    
@{    
    ViewBag.Title = "Index";    
}    
<!DOCTYPE html>    
<html>    
<head>    
<meta name="viewport" content="width=device-width" />    
<title>ENROLLMENT</title>    
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"/>    
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>    
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
<link href="../../Content/StyleSheet.css" rel="stylesheet" type="text/css" />    
<script type="text/javascript">    
    
    $(document).ready(function () {    
        $.ajax({    
    
            type: 'POST',    
            URL: '/UserLogin/UserLogin',    
            data: data,    
            dataType: 'JSON',    
            success: function (data) {    
                datadata = data.status    
                if (status == "1") {    
                    window.location.href = '@Url.Action("Index","UserLogin")';    
                }    
            }    
        });    
    });    
</script>    
</head>    
    
<body>    
<!------ Include the above in your HEAD tag ---------->    
@using (Html.BeginForm("Index", "UserLogin", FormMethod.Post))    
{    
@Html.AntiForgeryToken()      
<div class="container register">    
                <div class="row">    
                    <div class="col-md-3 register-left">    
                        <img src="https://image.ibb.co/n7oTvU/logo_white.png" alt=""/>    
                        <h3>Welcome</h3>    
                        <p>This Example is for learning MVC Basic Login and Registration Using ADO.NET.</p>    
                    </div>    
                    <div class="col-md-9 register-right">    
                        <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist">    
                            <li class="nav-item">    
                                <a class="nav-link active" id="home-tab" data-toggle="tab" href="../Enrollment/Index" role="tab" aria-controls="home" aria-selected="true">Register</a>    
                            </li>    
                            <li class="nav-item">    
                                <a class="nav-link" id="profile-tab" data-toggle="tab" href="../UserLogin/Index" role="tab" aria-controls="profile" aria-selected="false">Login</a>    
                            </li>    
                        </ul>    
                        <div class="tab-content" id="myTabContent">    
                            <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">    
                                <h3 class="register-heading">Login as a Employee</h3>    
                                <div class="row register-form">    
                                    <div class="col-md-6">    
                                       <div class="form-group">    
                                            @Html.TextBoxFor(e => e.Email, new { @class = "form-control", placeholder = "Your Email *" })    
                                            @Html.ValidationMessageFor(e => e.Email)    
                                        </div>    
                                        <div class="form-group">    
                                           @Html.PasswordFor(e => e.Password, new { id = "password", @class = "form-control", placeholder = "Password *" })    
                                             <span id="result"></span>    
                                             @Html.ValidationMessageFor(e => e.Password)    
                                        </div>    
                                    <div class="col-md-6">    
                                         <input type="submit" class="btnLogin"  value="Login"/>    
                                    </div>    
                                            
                                    </div>    
                                        
                                </div>    
                            </div>    
                         </div>    
                    </div>    
                </div>    
                   
               <script type="text/javascript">    
               $(function () {    
                     var msg = '@ViewData["result"]';    
                     if (msg == '1')    
                     {    
                         alert("User Details Inserted Successfully");    
                         window.location.href = "@Url.Action("Index", "UserLogin")";    
                      }    
                  });    
               </script>    
               }    
            </div>    
         }    
   </body>    
</html>    

2

Answers


  1. In .net core below way we can set & get session value.

    For set session value please consider below syntax.

    Example : HttpContext.Session.SetString("login", "pass our value");

    For get session value inside view, please consider below syntax

    Example:

    @using Microsoft.AspNetCore.Http
    @inject IHttpContextAccessor httpContextAccessor

    @httpContextAccessor.HttpContext.Session.GetString("login")

    Login or Signup to reply.
  2. Pior to .Net 6, We configure service and middleware in Startup.cs file, But after .Net 6, Asp.Net-Core remove Startup.cs file and use Program.cs file to configure service and middleware.

    So you not need to add Startup.cs file manually, Configure session in Program.cs like this:

    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    //other service
    
    builder.Services.AddSession(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    
    //other middleWare
    app.UseSession();
    
    //other middleWare
    
    app.Run();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search