gpt4 book ai didi

c# - View 中的 session 变量

转载 作者:行者123 更新时间:2023-12-05 01:00:25 25 4
gpt4 key购买 nike

前段时间我创建了一些简单的使用 session 登录。这是一个 MVC 应用程序,但如果我是正确的,它带有 .net 框架 4.6。我可以在那里使用类似

的东西
<h2>@Session["ID"]</h2>

来自 session 变量的 ID 应该在 h2 标签中。但现在我尝试使用 .net core 2.0 构建相同的版本。

我的startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<L2Context>(options =>
options.UseSqlite("Data Source=test.db"));

services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseSession();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

Controller 将数据保存到 session 中:

[HttpPost]
public IActionResult Login(Users user)
{
var optionsBuilder = new DbContextOptionsBuilder<L2Context>();
optionsBuilder.UseSqlite("Data Source=test.db");

using (L2Context db = new L2Context(optionsBuilder.Options))
{
var user = db.Users.Single(u => u.Login == user.Login && u.Password == user.Password);
if (user != null)
{
HttpContext.Session.SetString("ID", user.ID.ToString());
HttpContext.Session.SetString("Login", user.Login.ToString());
return RedirectToAction(nameof(LoggedIn));
}
else
{
ModelState.AddModelError("", "Login or password is invalid");
}
}
return View();
}

登录查看:

@{
ViewData["Title"] = "LoggedIn";
}

<h4> Hello @Session["Login"]</h4>

那么,我这里有什么错误吗?上次我用的时候,我觉得它工作得很好。

我明白了:

error CS0103: The name 'Session' does not exist in the current context

最佳答案

在 ASP.NET Core 中, View 默认无权访问 HttpContext 对象的 Session 属性。您可以通过在 View 中导入 Http 命名空间来访问它:

//import the namespace to make the class available within the view
@using Microsoft.AspNetCore.Http

然后您可以访问 HttpContext 对象的 Session 属性:

<h4> Hello @HttpContext.Session.GetString("Login")</h4>

关于c# - View 中的 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com