InvalidOperationException: 该应用程序或请求尚未配置会话。

huangapple go评论122阅读模式
英文:

.net 7 Visual Studio Code : InvalidOperationException: Session has not been configured for this application or request

问题

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.

我按照这个教程的示例(https://www.c-sharpcorner.com/article/simple-login-and-registration-form-in-asp-net-mvc-using-ado-net/)创建了一个简单的C# MVC .Net Web应用程序的注册和登录页面。

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

我成功实现了用户注册到由Xampp托管的本地mysql数据库。

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

但是对于UserLoginController,我遇到了以下错误:

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[] )

InvalidOperationException: 尚未为此应用程序或请求配置会话。
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")

Startup.cs(我不得不手动添加,因为"dotnet new mvc -o Project"没有添加它)

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

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

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

<details>
<summary>英文:</summary>

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&#39;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(&quot;Email&quot;, e.Email);
    lambda_method28(Closure , object , object[] )

Below are some of my code and configuration:

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

    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 =&gt;
                {
                    options.Cookie.HttpOnly = true;
                    options.Cookie.IsEssential = true;
                });
    
                services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); // 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 = &quot;Server=localhost;Port=3306;Database=database;Uid=root;Pwd=root;&quot;;
                using (MySqlConnection con = new MySqlConnection(connectionString))
                {
                    string sqlQuery = &quot;SELECT Email, Password FROM Enrollment WHERE Email = @Email AND Password = @Password&quot;;
                    con.Open();
                    MySqlCommand cmd = new MySqlCommand(sqlQuery, con);
                    cmd.Parameters.AddWithValue(&quot;@Email&quot;, e.Email);
                    cmd.Parameters.AddWithValue(&quot;@Password&quot;, e.Password);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    
                    if (reader.Read())
                    {
                        HttpContext.Session.SetString(&quot;Email&quot;, e.Email);
                        return RedirectToAction(&quot;Welcome&quot;);
                    }
                    else
                    {
                        ViewData[&quot;Message&quot;] = &quot;User Login Details Failed!!&quot;;
                    }
    
                    con.Close();
                }
    
                return View();
            }
    
            [HttpGet]
            public ActionResult Welcome()
            {
                Enroll user = new Enroll();
                DataSet ds = new DataSet();
    
                string connectionString = &quot;Server=localhost;Port=3306;Database=database;Uid=root;Pwd=root;&quot;;
                using (MySqlConnection con = new MySqlConnection(connectionString))
                {
                    using (MySqlCommand cmd = new MySqlCommand(&quot;sp_GetEnrollmentDetails&quot;, con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue(&quot;@Email&quot;, HttpContext.Session.GetString(&quot;Email&quot;));
                        con.Open();
                        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                        adapter.Fill(ds);
                        List&lt;Enroll&gt; userlist = new List&lt;Enroll&gt;();
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            Enroll uobj = new Enroll();
                            uobj.ID = Convert.ToInt32(row[&quot;ID&quot;].ToString());
                            uobj.FirstName = row[&quot;FirstName&quot;].ToString();
                            uobj.LastName = row[&quot;LastName&quot;].ToString();
                            uobj.Password = row[&quot;Password&quot;].ToString();
                            uobj.Email = row[&quot;Email&quot;].ToString();
                            uobj.PhoneNumber = row[&quot;Phone&quot;].ToString();
                            uobj.SecurityAnswer = row[&quot;SecurityAnswer&quot;].ToString();
                            uobj.Gender = row[&quot;Gender&quot;].ToString();
    
                            userlist.Add(uobj);
                        }
                        user.Enrollsinfo = userlist;
                    }
                    con.Close();
                }
    
                ViewBag.Email = HttpContext.Session.GetString(&quot;Email&quot;);
    
                return View(user);
            }
    
    
            public ActionResult Logout()
            {
                HttpContext.Session.Clear();
                return RedirectToAction(&quot;Index&quot;, &quot;UserLogin&quot;);
            }
        }
    } 

Index.cshtml

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

</details>


# 答案1
**得分**: 1

在.Net 6之前,我们在`Startup.cs`文件中配置服务和中间件,但在.Net 6之后,Asp.Net-Core移除了`Startup.cs`文件,而是使用`Program.cs`文件来配置服务和中间件。

因此,您不需要手动添加`Startup.cs`文件,可以像这样在`Program.cs`中配置会话:

```csharp
var builder = WebApplication.CreateBuilder(args);

// 向容器添加其他服务

builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();

// 配置HTTP请求管道

// 添加其他中间件

app.UseSession();

// 添加其他中间件

app.Run();
英文:

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 =&gt;
{
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();

答案2

得分: 0

在 .NET Core 中,我们可以使用以下方式来设置和获取会话值。

要设置会话值,请考虑以下语法。

示例:HttpContext.Session.SetString("login", "传入我们的值");

要在视图中获取会话值,请考虑以下语法。

示例:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

@httpContextAccessor.HttpContext.Session.GetString("login")
英文:

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")

huangapple
  • 本文由 发表于 2023年6月26日 03:01:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定