[英]Get current logged in user from within a view
我有一個view.cshtml,它的頂部有一個@model .... SportTeam。 我只想從當前登錄用戶的AspNetUser表中檢查ID。
我是否必須在Controller中執行此操作,然后將其傳遞給View? 還是可以直接在視圖中查看?
在視圖中,我可以鍵入User.Identity,但是在Identity之后,我得到的所有內容都是“名稱”,並且我需要ID。
是的,您可以在視圖中獲取用戶-您可以在視圖中運行所需的任何代碼,但不應這樣做。 MVC的全部目的是保持視圖盡可能的愚蠢。 因此,應將盡可能多的邏輯轉移到控制器中,並通過模型類傳遞所需的信息。
如果您不喜歡MVC,請看一下Razor頁面,這些頁面僅用視圖代替了MVC。
下面的方法將為您提供一個已登錄用戶ID作為字符串,然后您可以在模型中擁有分配該字符串的屬性,然后可以將其傳遞給視圖。
public string GetLoggedInUserId()
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>()
.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
return user.Id;
}
您將必須導入以下內容:
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
我同意@Christian。 將其放入控制器中。 但是,如果您需要以簡單的方式獲取用戶ID,則可以為IIdenty添加和擴展方法。 像這樣:
public static class IdentityExtensions
{
public static Guid GetUserId(this IIdentity identity)
{
var claim = ((ClaimsIdentity) identity).FindFirst(x => x.Type.ToLowerInvariant().Contains("nameidentifier"));
// Test for null to avoid issues during local testing
return claim != null ? Guid.Parse(claim.Value) : throw new ArgumentNullException(nameof(claim));
}
}
上面的代碼為我工作。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.