asp.net - 云应用程序 ASP.Net MVC 中的 session 维护

标签 asp.net asp.net-mvc asp.net-mvc-4 azure cloud

我正在使用 razor 语法在 ASP.Net MVC 4 上开发 Web 应用程序。我必须将其部署在云上,可能是在 Azure 上。 我对 MVC 的登录方案感到很困惑。我们必须处理多个架构,因此我们不使用 ASP.Net 提供的membership

我知道 session 维护,并且我在 Web 表单中使用了它,但是 session 在云方面存在一些严重问题。

保存用户名和 session 数据的最佳方法是什么?

最佳答案

我会避免使用 session 状态来存储用户信息甚至 session 数据,因为这会降低您的应用程序的可扩展性。

如果您想存储用户名、显示名称、电子邮件地址……我建议基于声明的身份验证。 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, "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40353325322e212d2500232f2d30212e396e232f2d" rel="noreferrer noopener nofollow">[email protected]</a>"),
        new Claim(ClaimTypes.Role, "RoleA"),
        new Claim(ClaimTypes.Role, "RoleB"),
        new Claim(OfficeLocationClaimType, "5W-A1"),
    };
    return claims; }

就 session 数据而言,您可能需要考虑 Windows Azure 角色内缓存或 Windows Azure 缓存服务。甚至还有一个 session 状态提供程序可以将 session 状态存储在缓存中:http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx .

但是您可以通过使用缓存键轻松地自己完成此操作,而无需使用 session 状态,如下所示:

myCache.Put(user.Id + "_Friends", friendsList);

关于asp.net - 云应用程序 ASP.Net MVC 中的 session 维护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19972477/

相关文章:

asp.net-mvc-4 - EF 代码优先、模型优先还是数据库优先?对于许多变化的中大型应用程序

c# - 无法将类型 'System.Collections.Generic.List<website.Class1>' 转换为 'System.Collections.Generic.List<library.Class1>'

c# - ASP.NET MVC : how to make all unspecified URLs direct to one controller

ASP.NET:重写 IIS 对 "expect 100" header 的响应?

asp.net-mvc - MVC 中 HTML 帮助页面的链接

asp.net-mvc - 在 MVC 2 RC 区域中设置默认 Controller 时遇到问题

asp.net - ext.net 中的客户端验证和显示字段样式

c# - 由于 MySql,.NET MVC4 应用程序无法运行

c# - 在 Visual Studio 的同一端口上运行两个应用程序

c# - 应用架构-管理员注册和管理