【问题标题】:Azure: Is the HttpContext.Current.Session object shared by all WebRole instances?Azure:所有 WebRole 实例是否共享 HttpContext.Current.Session 对象?
【发布时间】:2013-03-07 12:32:48
【问题描述】:

我正在 Windows Azure 中使用 多个实例 测试 WebRole 以测试负载平衡器。我必须对用户进行身份验证的代码如下:

    protected void Application_AcquireRequestState(Object sender, EventArgs e)
    {
        HttpCookie authCookie = 
            HttpContext.Current.Request.Cookies
               [FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = 
                FormsAuthentication.Decrypt(authCookie.Value);

            SetUserCredentials(authTicket.Name, authTicket.UserData);
        }
    }

    private void SetUserCredentials(string userName, string securityConfig)
    {
        Credentials auth = GetSessionCredentials();

        if (auth == null && HttpContext.Current.Session != null)
        {
            log.DebugFormat("Credentials not available in session variable. Building credentials to __SessionSID.");

            SID sid = 
               AuthenticationHelper.Get().
                  GetAuthenticatedSIDFromName(userName, securityConfig);

            if (sid == null)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
                return;
            }

            auth = new Credentials(sid);

            if (HttpContext.Current.Session != null)
            {
                log.DebugFormat("Saving credentials in a session variable");
                HttpContext.Current.Session.Add("__SessionSID", auth);
            }
        }

        log.DebugFormat("Time setting user credentials for user: {0} {1}ms", userName, Environment.TickCount - ini);
    }

    private Credentials GetSessionCredentials()
    {
        if (HttpContext.Current == null)
            return null;
        if (HttpContext.Current.Session == null)
            return null;

        return HttpContext.Current.Session["__SessionSID"] as Credentials;
    }

这是我的问题。我在 Azure 中使用两个实例测试了 WebRole:

  • 假设我登录并且 WebRole 实例 A 执行身份验证。
  • 当我发出新请求,并且请求转到 WebRole 实例 B 时,Current.Request.CookiesHttpContext.Current.Session["__SessionSID"] 中的 authTicket 正常。

谁能解释一下?我在所有 WebRole 实例之间共享会话?

【问题讨论】:

    标签: .net asp.net-mvc azure


    【解决方案1】:

    这一切都归结为Session State Provider 配置。

    通常您必须实现自定义提供程序(通常是 Windows Azure Cache 或 SQL Azure),以允许跨多个实例的持久会话数据。

    http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx

    一旦登录(无论在哪个实例上),您都会收到一个包含 SessionID 的 cookie。

    对任何实例的进一步请求将导致应用程序从配置的提供程序请求您的会话数据。

    【讨论】:

    • 但是我在上面粘贴的代码,它在没有实现任何自定义提供程序的情况下工作。我最初的问题是为什么?
    • 您的代码只是检查 Session 不为空(这不应该与会话状态无关)。您还在会话日期中添加了一些值,但您不会在以后的任何地方检查/记录/比较它们以验证您在各个实例中获得相同的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2018-09-21
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多