簡體   English   中英

如何在Asp.net Mvc中獲得當前登錄用戶的角色?

[英]How to get the roles of current logged-in user in Asp.net Mvc?

我正在編寫代碼以在if-condition內獲取Login方法中的角色,但未返回用戶角色。

 public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {

            List<string> r = Roles.GetRolesForUser().ToList();
            if(r.Contains("Admin"))
            {
                return RedirectToAction("About", "Home");
            }
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

當您調用WebSecurity.Login ,不會自動填充用戶的身份驗證和角色數據。 而是將它們寫入身份驗證cookie,並且只能在下一個請求時讀取。

這意味着您只能在登錄后將用戶重定向到下一頁(通常是Home/Index )后才能從Roles.GetRolesForUser()讀取。 這是因為用戶發出的下一個請求(無論可能是什么)現在都將附加身份驗證cookie。

當前請求(〜/ login.aspx)沒有附加任何身份驗證cookie,因此Roles.GetRolesForUser()和類似函數將始終不返回任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM