Asp.net mvc 4 MVC4-在控制器后操作期间,WebSecurity.CurrentUserId将丢失它';s值,并变为-1

Asp.net mvc 4 MVC4-在控制器后操作期间,WebSecurity.CurrentUserId将丢失它';s值,并变为-1,asp.net-mvc-4,Asp.net Mvc 4,不知何故,在这个控制器中,在SaveChanges之后,CurrentUserId变成了-1。 数据post工作,并且CurrentUserId具有其登录值(例如8888),但是在SQL插入之后,WebSecurity.CurrentUserId变为-1。有线索吗?在调试期间,我找不到位置和原因 // POST: /Account/Edit [HttpPost] [ValidateInput(false)] public ActionResult Edit(Use

不知何故,在这个控制器中,在SaveChanges之后,CurrentUserId变成了-1。 数据post工作,并且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);
        }
    }

这将始终返回-1,您需要的是下面的代码

 int currentuserid = WebSecurity.GetUserId(username);
然后,您可以验证上面的userid是否与模型中的userid匹配,以防止用户更改其他用户的代码

作为补充。我在我的基本控制器中使用此选项:

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);
    }

您正在执行autoincrement
WebSecurity。CurrentUserId==-1
表示当前没有登录的用户。价值在哪里变化?在同一控制器中,在保存更改之后和重定向之前?或者在你重定向到的页面上?不,不是我需要的。你的脸,不是我需要的。您的建议-仅允许编辑您自己的内容-已通过customAttribute[AuthorizeCreator]实现。