Azure:所有WebRole实例共享HttpContext.Current.Session对象吗?

时间:2013-03-07 12:32:49

标签: .net asp.net-mvc azure

我正在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实例之间共享会话?

1 个答案:

答案 0 :(得分:2)

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

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

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

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

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

相关问题