简体   繁体   English

Session 在 ASP.NET 核心 MVC

[英]Session in ASP.NET Core MVC

I am migrating an ASP.NET MVC application to ASP.NET Core MVC.我正在将 ASP.NET MVC 应用程序迁移到 ASP.NET Core MVC。

In ASP.NET MVC, I am using some Session variables to store or get values like:在 ASP.NET MVC 中,我使用了一些Session变量来存储或获取如下值:

Session["UserID"] = user.UserName;
Session["Role"] = role[0].ROLE_DESCRIPTION;
ViewData["LEVEL"] = Session["LEVEL"];

But after converting, I get an error:但是转换后,我得到一个错误:

The name 'Session' does not exist in the current context当前上下文中不存在名称“会话”

Also, I need to have replacement for this as well in the .cshtml file:此外,我还需要在.cshtml文件中对此进行替换:

var UserName = "@Session["Name"]";

Is there any other method in ASP.NET Core MVC to store or get values on those variables without changing the behavior? ASP.NET Core MVC 中是否还有其他方法可以在不改变行为的情况下存储或获取这些变量的值?

You need to add session middleware in your configuration file您需要在配置文件中添加 session 中间件

public void ConfigureServices(IServiceCollection services)  
{  
     //........
    services.AddDistributedMemoryCache();  
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time   
    });  
    services.AddMvc();  
} 

public void ConfigureServices(IServiceCollection services)
{
    //......
    app.UseSession();
    //......
}

Then in your controller, you can然后在你的controller中,你可以

//set session 

HttpContext.Session.SetString(SessionName, "Jarvik");  
HttpContext.Session.SetInt32(SessionAge, 24);

//get session

ViewBag.Name = HttpContext.Session.GetString(SessionName);  
ViewBag.Age = HttpContext.Session.GetInt32(SessionAge); 
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM