英文:
.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'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>
</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 =>
{
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论