我可以将 UserId 保留在 User.Identity 中吗?MVC4 简单会员



我想知道SimpleMember是否将UserId保留在某个地方,或者如果没有,一旦派生数据,如何强制它保留。

我有一个简单的动作:

    [Authorize(Roles="User")]
    public ActionResult Create()
    {
        var ownerId = WebSecurity.GetUserId(User.Identity.Name);
        return View()
    }

我的迷你分析器说:

 DECLARE @0 nvarchar(4) = N'NICK'
 SELECT [UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = @0)   
 DECLARE @0 int = 2
 SELECT r.RoleName FROM webpages_UsersInRoles u, webpages_Roles r Where 
 (u.UserId = @0 and u.RoleId = r.RoleId) GROUP BY RoleName 
 DECLARE @0 nvarchar(4) = N'NICK'
 SELECT [UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = @0)  

因此,我重复了对UserId的查询 - 首先获取角色,其次通过调用WebSecurity.GetUserId(User.Identity.Name);。有没有一种聪明的方法可以在调用 [授权] 后将 UserId 保存在某个地方?

我通常将我的用户配置文件包装在会话变量中。

 public static userProfile UserInfo
 {
     get { return HttpContext.Current.Session["UserInfo"] as userProfile; }
     set { HttpContext.Current.Session["UserInfo"] = value; }
 }

用户登录后查询UserProfile表并执行

UserInfo = QueryAsClass; //you need to map your sql to an object

到达那里后,您可以随时通过执行以下操作来访问它

UserInfo.userId

我将userProfile表作为应用程序中的对象类

编辑

我有这个代码,在用户登录后执行

using (var db = new DBEntities())
    {
        var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
        if (userId == -1) return;
        SessionHelpers.UserInfo = db.userProfiles.Single(x => x.userId == userId);
    }

我使用的是 EF5,并且我的模型中有userProfile表,因此如果不使用 EF,则需要调整此部分。

当我需要userId时,我只是SessionHelpers.UserInfo.userId。这让我可以在需要时获取所有用户配置文件信息,而无需重新查询数据库。

当然,如果您更改了用户配置文件中的某些内容,则还需要更新会话变量。

您可能需要具有更高级的逻辑并检查会话是否为空(我在其他地方正在这样做)。

最新更新