c# - 如何在 ASP.NET Core 2.x 中存储和检索 session 状态的对象?

标签 c# asp.net-core

如何将 EmployeeId 和 DesignationId 添加到对象中,然后从 session 状态中检索它?

这是我的登录 Controller 代码:

DataTable dt = sql.GetDataTable("select * from EmpDetails where EmailId = '" + EmailId + "'");
string strempstatus = dt.Rows[0]["Status"].ToString();
string EmpStatus = strempstatus.TrimEnd();

//Models.UserDetails detail = new Models.UserDetails();

if (EmpStatus == "Verified")
{
    //i want to create object which store below two variable value
    string EmployeeId = dt.Rows[0]["Id"].ToString();
    string DesignationId = dt.Rows[0]["D_Id"].ToString();

    //I want to stored object in below session
    HttpContext.Session.SetString("EmployeeData", EmployeeId);

    HttpContext.Session.SetInt32("EmployeeID", Convert.ToInt32(EmployeeId));
    //For Destroy Session
    //HttpContext.Session.Remove("EmployeeID");

    Int32? Saved = HttpContext.Session.GetInt32("EmployeeID");

    if (DesignationId == "1")
    {
        return RedirectToAction("Index", "AdminDashboard");
    }
    else
    {
        return RedirectToAction("Index", "UserDashboard");
    }
}

最佳答案

在 Startup.cs 的“Configure”方法下,添加以下行:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}

在ConfigureServices方法下,添加以下行:

public void ConfigureServices(IServiceCollection services)
{
  //Added for session state
  services.AddDistributedMemoryCache();
   
  services.AddSession(options =>
  {
  options.IdleTimeout = TimeSpan.FromMinutes(10);               
  });
}

为了在 .NET Core session 中存储复杂对象,请按照以下步骤操作:

创建您的对象类型的模型类(在您的例子中为 EmployeeDetails):

public class EmployeeDetails
{
    public string EmployeeId { get; set; }
    public string DesignationId { get; set; }
}

然后创建一个 SessionExtension 帮助器来设置和检索 JSON 格式的复杂对象:

public static class SessionExtensions
{
  public static void SetObjectAsJson(this ISession session, string key, object value)
   {
     session.SetString(key, JsonConvert.SerializeObject(value));
   }
    
   public static T GetObjectFromJson<T>(this ISession session, string key)
   {
     var value = session.GetString(key);
     return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
   }
}

最后将 session 中的复杂对象设置为:

var employee = new EmployeeDetails();
employee.EmployeeId = "1";
employee.DesignationId = "2";

HttpContext.Session.SetObjectAsJson("EmployeeDetails", employee);

要在 session 中检索复杂对象:

var employeeDetails = HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
int employeeID = Convert.ToInt32(employeeDetails.EmployeeId);
int designationID= Convert.ToInt32(employeeDetails.DesignationId);

编辑:

我已经看到很多问题,其中 Session 数据无法在 View 上访问,因此我也更新了有关如何实现此目的的答案。为了在 View 上使用 Session 变量,您需要将 IHttpContextAccessor 实现注入(inject)到 View 中并使用它根据需要获取Session对象:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
    //Get object from session
    var mySessionObject = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
 }

<h1>@mySessionObject.EmployeeId</h1>
<h1>@mySessionObject.DesignationId</h1>

关于c# - 如何在 ASP.NET Core 2.x 中存储和检索 session 状态的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55220812/

相关文章:

c# - 如何在不包含/加载整个集合的情况下获取 Entity Framework 模型中列表的计数?

c# - 下面的PUT方法代码中是否需要int id?

c# - 更改 ASP.NET Core MVC 中的默认 cookie 名称

c# - 根据定义,值类型是不可变的吗?

c# - 如何从头开始创建声音 C#

javascript - 在 WInRT 应用程序中下载 WebView 内容

c# - 在 ASP.NET Core 3 的类库中创建 TagHelper

c# - ASP.Net Core 应用程序和 Environment.GetEnvironmentVariables() 奇怪的行为

c# - 为什么 C# 接口(interface)不能包含字段?

java - 用 C# 解密用 Java 加密的密码