我正在 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.Cookies
中的 authTicket和HttpContext.Current.Session["__SessionSID"]
还好。
有人可以解释一下吗?我的 session 在所有 WebRole 实例之间共享吗?
最佳答案
这一切都取决于 session 状态提供程序
配置。
通常,您必须实现自定义提供程序(通常是 Windows Azure 缓存或 SQL Azure)以允许跨多个实例保留 session 数据。
http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx
登录后(无论在哪种情况下),您都会收到一个带有 SessionID 的 cookie。
对任何实例的进一步请求将导致应用程序从配置的提供程序请求您的 session 数据。
关于.net - Azure:HttpContext.Current.Session 对象是否由所有 WebRole 实例共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271344/