我有一个UserProfile类,它是为每个新注册用户生成和更新的。在布局页面中存储/缓存该对象的正确技术是什么,以便在用户登录并验证后每次加载新页面时都可以使用它?
我目前正在将其加载到模型中
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (User.Identity.IsAuthenticated)
{
var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
lvm.LoggedInUserProfile =
MyProject.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);
var iconSource = string.Empty; //= ConfigurationHelpers.UserIcons.FemaleUserIconSource;//var profile = MyProject.UserService.UserHelpers.GetUserProfileIncluding(User.Identity.GetUserId());
if (lvm.LoggedInUserProfile != null)
{
if (lvm.LoggedInUserProfile.AvatarUrl != null)
{
iconSource = lvm.LoggedInUserProfile.Gender == Gender.Female ? ConfigurationHelpers.UserIcons.FemaleUserIconSource : ConfigurationHelpers.UserIcons.MaleUserIconSource;
}
iconSource = lvm.LoggedInUserProfile.AvatarUrl;
}
if (lvm.LoggedInUserProfile != null) ViewData.Add("FullName", lvm.LoggedInUserProfile.FirstName);
ViewData.Add("IconSource", iconSource);
ViewData.Add("ViewModel", lvm);
}
base.OnActionExecuted(filterContext);
}
但这似乎已经运行了几十次而且看起来很浪费。
答案 0 :(得分:0)
使用Session,正如两位评论者所建议的那样,似乎是要走的路。现在该代码只被击中一次。
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (User.Identity.IsAuthenticated && Session["LayoutViewModel"] == null)
{
var lvm = new LayoutViewModel { AppUserId = User.Identity.GetUserId() };
lvm.LoggedInUserProfile =
MyProject.Services.UserService.UserHelpers.GetProfileForLoggedInUser(lvm.AppUserId);
if (lvm.LoggedInUserProfile != null)
{
Session["LayoutViewModel"] = lvm;
}
else
{
Session["LayoutViewModel"] = null;
}
}
base.OnActionExecuted(filterContext);
}
在布局视图中,确保在检索时转换会话。
@using MyProject.ViewModels
@{
var svm = (LayoutViewModel)Session["LayoutViewModel"];
}