当用户登录我的网站时,我想缓存一些数据,例如电子邮件,确认状态,移动确认状态等。因为我不想在每个页面请求中都获取此数据。要求是用户必须先确认电子邮件和手机才能做任何事情。
我正在使用这样的代码:

public static class CachedData
{
    public static bool IsEmailConfirmed
    {
        get
        {
            if (HttpContext.Current.Session["IsEmailConfirmed"] == null)
                Initialize();
            return Convert.ToBoolean(HttpContext.Current.Session["IsEmailConfirmed"]);
        }
        set
        {
            HttpContext.Current.Session["IsEmailConfirmed"] = value;
        }
    }

    public static bool IsMobileConfirmed
    {
        get
        {
            if (HttpContext.Current.Session["IsMobileConfirmed"] == null)
                Initialize();
            return Convert.ToBoolean(HttpContext.Current.Session["IsMobileConfirmed"]);
        }
        set
        {
            HttpContext.Current.Session["IsMobileConfirmed"] = value;
        }
    }

    public static void Initialize()
    {
        UserAccount currentUser = UserAccount.GetUser();
        if (currentUser == null)
            return;

        IsEmailConfirmed = currentUser.EmailConfirmed;
        IsMobileConfirmed = currentUser.MobileConfirmed;
    }
}


我有PageBase类,所有页面类都从中驱动。我在CachedData类中使用类PageBase

public class PageBase : Page
{
    protected override void OnInit(EventArgs e)
    {
        if (authentication.Required && User.Identity.IsAuthenticated && !IsPostBack)
        {
            if (CachedData.HasProfile && (!CachedData.IsEmailConfirmed || !CachedData.IsMobileConfirmed) && !Request.Url.AbsolutePath.ToLower().EndsWith("settings.aspx"))
                Response.Redirect("/settings-page", true);
        }
    }
}


可能是奇怪的,但是此代码有时可能会出错,并重定向到用户确认的电子邮件和手机的设置页面。
有没有更好的解决方案。

最佳答案

我认为,如果这是您的逻辑,则应创建一个对象UserInfo。像这样:

public class UserInfo
{
    public string Name {get; set; }
    public bool IsEmailConfirmed {get; set; }
    public bool IsMobileConfirmed {get; set; }
    ....
}


然后将此对象设置为会话。现在!在BLL中对用户记录执行任何操作时,应重新填充新的UserInfo实例,并替换会话中的旧实例。这样,您的用户信息将是最新的,并且将始终有效。

但是您的问题可能出自以下事实:您使用Web场并且会话未同步。您需要使用粘性会话,以便在同一服务器上处理来自唯一用户的每个请求。现在有一个叫做App Fabric的东西。它在类固醇上缓存。它可以在另一台服务器的缓存中找到一个项目。

10-02 01:42
查看更多