簡體   English   中英

獲取asp.net mvc 4中登錄用戶的id

[英]Get id of the logged in user in asp.net mvc 4

我正在使用asp.net SimpleMembership 我試圖在ViewBag顯示登錄用戶的ViewBag 出於某種原因,我為ProvidedUserKey()獲取了NULL。 這是我的代碼,

調節器

[HttpPost]
    public ActionResult Login(ClientReg user)
    {            
        if (ModelState.IsValid)
        {
            FormsAuthentication.SetAuthCookie(user.username, false);
            return RedirectToAction("Index");
        }
        else
        {
            return RedirectToAction("Login");
        }
    }

[Authorize]
    public ActionResult Index()
    {
        string userId = Membership.GetUser().ProviderUserKey.ToString();    //Null error in this line
        ViewBag.UserId = userId;
        return View();
    }

視圖

<div class="container">
    @ViewBag.UserId
</div>

如何獲取登錄用戶的ID?

使用此類而不是成員資格:

WebSecurity.GetUserId(User.Identity.Name);

Simple Membership繼承WebSecurity實例,是獲取用戶數據的更可靠方法。

object id = Membership.GetUser().ProviderUserKey

暫無
暫無

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

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