如何在不同的控制器视图中使用会话数据?
How to use session Data in a different Controller View?
ApplicationDBContext.cs
public DbSet<Register> RegisterAccount { get; set; }
注册模型
public class Register
{
[Key]
public int RegisterId { get; set; }
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid e-mail address")]
public string Email { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
[MinLength(5, ErrorMessage = "Password length cannot be less than 5")]
public string Password { get; set; }
[NotMapped] // Does not effect the database
[Compare("Password")]
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
}
我想在各种控制器中使用会话数据,我该如何管理?
LoginController.cs
public IActionResult Login(Login user)
{
if (ModelState.IsValid)
{
var obj = _db.RegisterAccount.Where(u => u.Email.Equals(user.Email) && u.Password.Equals(user.Password)).FirstOrDefault();
if (obj != null)
{
user.RegisterId = obj.RegisterId;
_db.LoginAccount.Add(user);
_db.SaveChanges();
HttpContext.Session.SetObjectAsJson("Register", obj);
return RedirectToAction("LoggedIn");
}
}
ModelState.AddModelError("", "Some Error Occured");
return RedirectToAction("Login");
}
public IActionResult LoggedIn()
{
var userDetails = HttpContext.Session.GetObjectFromJson<Register>("Register");
int? thisUserID = Convert.ToInt32(userDetails.RegisterId);
if (thisUserID != null)
{
TempData["Users"] = userDetails;
return View();
}
else
{
return RedirectToAction("Login");
}
}
SessionExtension.cs
public static class SessionExtension
{
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);
}
}
LoggedIn.cshtml 查看
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var userdetails = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register"); // userdetails is available
}
<h1>Hi @userdetails.Name</h1>
此处显示用户名。
假设我有另一个控制器主页,在索引视图中我想访问登录用户的详细信息,我该怎么做?我试过了
HomeController/Index.cshtml 视图
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var userdetails = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register"); // userdetails remains null
}
<h1>Hi @userdetails.Name</h1>
家庭控制器索引
public IActionResult Index()
{
return View();
}
我想要做的是在用户登录时在我的家庭控制器索引视图和我的登录控制器索引视图中显示用户名。
为了在您的 View
上显示您的 Session
,您可以将 IHttpContextAccessor
实现注入您的视图,并根据需要使用它来获取 Session
对象:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
//Get object from session
var mySessionObject = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register");
}
<h1>@mySessionObject.Name</h1>
//So on
您的案例不需要 TempData
,因为您已经在设置 Session
。 TempData
用于将变量从一个 Controller
操作持久化到另一个操作以在操作方法本身中使用它们。
关于 Session
在其他 Controller
中无法访问的问题,您需要添加 services.AddDistributedMemoryCache()
以便有地方存储您的 Session
数据。您可以在 MSDN
上阅读更多内容
在您的 Startup.cs
中,添加以下内容:
public void ConfigureServices(IServiceCollection services)
{
//Added for session state
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
}
ApplicationDBContext.cs
public DbSet<Register> RegisterAccount { get; set; }
注册模型
public class Register
{
[Key]
public int RegisterId { get; set; }
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid e-mail address")]
public string Email { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
[MinLength(5, ErrorMessage = "Password length cannot be less than 5")]
public string Password { get; set; }
[NotMapped] // Does not effect the database
[Compare("Password")]
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
}
我想在各种控制器中使用会话数据,我该如何管理?
LoginController.cs
public IActionResult Login(Login user)
{
if (ModelState.IsValid)
{
var obj = _db.RegisterAccount.Where(u => u.Email.Equals(user.Email) && u.Password.Equals(user.Password)).FirstOrDefault();
if (obj != null)
{
user.RegisterId = obj.RegisterId;
_db.LoginAccount.Add(user);
_db.SaveChanges();
HttpContext.Session.SetObjectAsJson("Register", obj);
return RedirectToAction("LoggedIn");
}
}
ModelState.AddModelError("", "Some Error Occured");
return RedirectToAction("Login");
}
public IActionResult LoggedIn()
{
var userDetails = HttpContext.Session.GetObjectFromJson<Register>("Register");
int? thisUserID = Convert.ToInt32(userDetails.RegisterId);
if (thisUserID != null)
{
TempData["Users"] = userDetails;
return View();
}
else
{
return RedirectToAction("Login");
}
}
SessionExtension.cs
public static class SessionExtension
{
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);
}
}
LoggedIn.cshtml 查看
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var userdetails = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register"); // userdetails is available
}
<h1>Hi @userdetails.Name</h1>
此处显示用户名。
假设我有另一个控制器主页,在索引视图中我想访问登录用户的详细信息,我该怎么做?我试过了
HomeController/Index.cshtml 视图
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var userdetails = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register"); // userdetails remains null
}
<h1>Hi @userdetails.Name</h1>
家庭控制器索引
public IActionResult Index()
{
return View();
}
我想要做的是在用户登录时在我的家庭控制器索引视图和我的登录控制器索引视图中显示用户名。
为了在您的 View
上显示您的 Session
,您可以将 IHttpContextAccessor
实现注入您的视图,并根据需要使用它来获取 Session
对象:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
//Get object from session
var mySessionObject = HttpContextAccessor.HttpContext.Session.GetObjectFromJson<Register>("Register");
}
<h1>@mySessionObject.Name</h1>
//So on
您的案例不需要 TempData
,因为您已经在设置 Session
。 TempData
用于将变量从一个 Controller
操作持久化到另一个操作以在操作方法本身中使用它们。
关于 Session
在其他 Controller
中无法访问的问题,您需要添加 services.AddDistributedMemoryCache()
以便有地方存储您的 Session
数据。您可以在 MSDN
在您的 Startup.cs
中,添加以下内容:
public void ConfigureServices(IServiceCollection services)
{
//Added for session state
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
});
}