如何在Session中存储对象,然后如何通过在Asp.netCore2.1中强制转换Session来获取值?

时间:2019-03-18 11:56:42

标签: c# asp.net-core

如何在登录时在对象中以及在会话中存储的对象中添加EmployeeId和DesignationId,以及在登录后如何在asp.net core 2.1中检索该EmployeeId和DesignationId ?????

这是我的登录控制器代码:

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");
    }
}

1 个答案:

答案 0 :(得分:1)

为了在.NET CORE中查看和检索您的Session变量:

在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);               
  });
}

设置会话字符串:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

../

HttpContext.Session.SetString("UserID", "Your user ID");

要获取会话变量(例如在剃刀页面中):

@Context.Session.GetString("UserID")

编辑

为了在.NET Core中的会话中存储复杂的对象,请执行以下步骤:

创建您的对象类型的模型类(在您的情况下为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);
            }
        }

然后最后将会话中的复杂对象设置为:

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

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

要在会话中检索复杂的对象,请执行以下操作:

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