4

不知何故,在这个控制器中,在 SaveChanges 之后,CurrentUserId 变为 -1。数据发布工作,并且 CurrentUserId 具有它的登录值(例如 8888),但在 SQL 插入之后,WebSecurity.CurrentUserId 变为 -1。有什么线索吗?在调试期间,我找不到位置和原因。

    // POST: /Account/Edit
    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Edit(UserProfile model)
    {
        if (ModelState.IsValid)
        {

            using (var context = new dbContext())
            {
                var id = WebSecurity.CurrentUserId;
                var account = context.UserProfiles.Find(id);
                UpdateModel(account);
                context.SaveChanges();
                return RedirectToAction("Index", "Account");
            }


        }
        else
        {
            return View(model);
        }
    }
4

1 回答 1

0

总是返回-1,你需要的是下面的代码

 int currentuserid = WebSecurity.GetUserId(username);

然后,您可以验证上面的用户 ID 是否与模型中的用户 ID 匹配,以防止用户更改其他用户代码

作为附加。我在我的基本控制器中使用它:

public int GetUserId()
    {
        var userid = "0";

        if (Request.IsAuthenticated && User.Identity.Name != null)
        {
            var membershipUser = Membership.GetUser(User.Identity.Name);
            if (membershipUser != null)
            {
                if (membershipUser.ProviderUserKey != null)
                {
                    userid = membershipUser.ProviderUserKey.ToString();
                }
            }
        }

        return Convert.ToInt32(userid);
    }
于 2013-09-11T21:28:26.557 回答