【问题标题】:What is the proper way to cache a user profile in the MVC5 layout page在 MVC5 布局页面中缓存用户配置文件的正确方法是什么
【发布时间】:2017-11-08 02:22:08
【问题描述】:

我有一个为每个新注册用户生成和更新的 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);
    }

但这似乎运行了几十次,似乎很浪费。

【问题讨论】:

  • 你可以试试会话
  • @codelover...在 MVC5 中?我认为这是一个网络表单的事情
  • @dinotom Session 在 MVC 中也有。
  • @codelover - 会话是not recommended for user profile data
  • @NightOwl888...为什么不呢?谷歌搜索显示 Session 为有效用法的大多数答案。

标签: c# asp.net-mvc caching asp.net-mvc-5


【解决方案1】:

正如两位评论者所建议的那样,使用 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"];
 }

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2010-12-08
    • 1970-01-01
    • 2010-10-21
    相关资源
    最近更新 更多