[英]AspNetCore.Identity RemoveFromRoleAsync does not remove role from user
[英]ViewComponent does not recognize AspNetCore.Identity "User"
我正在嘗試根據此處的這篇文章為一系列復選框創建一個 ViewComponent:
https://learn.microsoft.com/en-us/as.net/core/mvc/views/view-components?view=as.netcore-2.2
這個 SO 在這里回答: https://stackoverflow.com/a/42853705/2300177
對於我正在嘗試做的事情來說,這似乎是一個完美的案例場景。 但是,我創建了我的 ViewComponent 以包含 Identity UserManager
以獲取userId
:
using BlogPlayground.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace BlogPlayground.ViewComponents
{
public class LatestArticlesViewComponent : ViewComponent
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
public LatestArticlesViewComponent(ApplicationDbContext context, UserManager<IdentityUser> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task<IViewComponentResult> InvokeAsync()
{
string userId = _userManager.GetUserId(User);
var lastArticles = await _context.Article
.OrderByDescending(a => a.CreatedDate)
.Take(howMany)
.ToListAsync();
return View(lastArticles);
}
}
}
問題是當我調用此行時:
string userId = _userManager.GetUserId(User);
我收到一條User
錯誤,內容如下:
無法從“System.Security.Principal.IPrincipal”轉換為“System.Security.Claims.ClaimsPrincipal”
這個確切的代碼適用於我所有的控制器,我什至不知道User
來自哪里。 看起來很神奇,但我猜是 Identity 內在的某個地方? 還是我只是錯過了控制器中包含的某些內容? (我在我的控制器中搜索了“用戶”,但無法將其鏈接到任何東西。)
我正在使用 Pomelo MySQL nuget package 如果這有什么不同? 我不這么認為。
任何人都知道我錯過了什么以及如何消除這個錯誤?
更新:似乎它可以解決這個問題(至少它擺脫了錯誤):
string userId = _userManager.GetUserId(Request.HttpContext.User);
那是一回事嗎? 我缺少 using 語句嗎? Visual studio (2017) 通常會提示我所缺少的內容。
請確保在Startup
配置了services.AddDefaultIdentity
並啟用了app.UseAuthentication
Identity
。
這需要通過dependency injection
使其可用於應用程序,因此您可以將它加載到您的LatestArticlesViewComponent
。
請參閱此處的詳細信息: ASP.NET Core上的Identity簡介
您應該使用ViewComponent
的UserClaimsPrincipal
屬性而不是User
屬性,因此
string userId = _userManager.GetUserId(UserClaimsPrincipal);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.