我正在將 ASP.NET MVC 應用程式遷移到 ASP.NET Core MVC。
在 ASP.NET MVC 中,我使用一些Session變數來存盤或獲取值,例如:
Session["UserID"] = user.UserName;
Session["Role"] = role[0].ROLE_DESCRIPTION;
ViewData["LEVEL"] = Session["LEVEL"];
但轉換后,我得到一個錯誤:
當前背景關系中不存在名稱“會話”
此外,我還需要在檔案中對此進行替換.cshtml:
var UserName = "@Session["Name"]";
ASP.NET Core MVC 中是否還有其他方法可以在不改變行為的情況下存盤或獲取這些變數的值?
uj5u.com熱心網友回復:
您需要在組態檔中添加會話中間件
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();
//......
}
然后在你的控制器中,你可以
//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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425444.html
標籤:C# asp.net-mvc asp.net-core-mvc
