我会避免使用会话状态来存储用户信息甚至会话数据,因为这会降低您的应用程序的可扩展性。
如果您想存储用户名、显示名、电子邮件地址……我建议使用基于声明的身份验证。 Brock Allen 写了一篇很棒的介绍文章来帮助您入门:Replacing forms authentication with WIF’s session authentication module (SAM) to enable claims aware identity。
主要思想是你分发一个 cookie(就像表单身份验证一样):
Claim[] claims = LoadClaimsForUser(username);
var id = new ClaimsIdentity(claims, "Forms");
var cp = new ClaimsPrincipal(id);
var token = new SessionSecurityToken(cp);
var sam = FederatedAuthentication.SessionAuthenticationModule;
sam.WriteSessionTokenToCookie(token);
这个 cookie 代表一个 ClaimIdentity,它可以包含一个或多个声明,如电子邮件地址等......
private Claim[] LoadClaimsForUser(string username) {
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Email, "username@company.com"),
new Claim(ClaimTypes.Role, "RoleA"),
new Claim(ClaimTypes.Role, "RoleB"),
new Claim(OfficeLocationClaimType, "5W-A1"),
};
return claims; }
就会话数据而言,您可能需要考虑 Windows Azure 角色内缓存或 Windows Azure 缓存服务。甚至还有一个 Session State Provider 可以将会话状态存储在缓存中:http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx。
但是您可以通过使用缓存键轻松地自己完成此操作,而无需使用会话状态,如下所示:
myCache.Put(user.Id + "_Friends", friendsList);