无法从 System.security.claims.claimsPrincipal 转换为 Scheduler.Areas.Identity.Data

ele*_*tmg 4 model-view-controller identity controller asp.net-core

我正在尝试获取当前用户 ID,以便我的事件索引页面将仅显示来自当前用户的事件。

我的 HttpContext.User 在我的事件控制器的索引内出现错误“无法从 System.security.claims.claimsPrincipal 转换为 Scheduler.Areas.Identity.Data”。

var userId = await _userManager.GetUserIdAsync(HttpContext.User);
Run Code Online (Sandbox Code Playgroud)

这是我的 EventsController 中的代码:

public EventsController(SchedulerDbContext context, UserManager<SchedulerUser> userManager)
{
    _context = context;
    _userManager = userManager;
}

// GET: Events
[Authorize]
public async Task<IActionResult> Index()
{
    var userId = await _userManager.GetUserIdAsync(HttpContext.User);
    return View(await _context.Events.Where(g => g.SchedulerUser == userId).ToListAsync());
}
Run Code Online (Sandbox Code Playgroud)

我应该去哪里寻找解决这个问题的方法?如果需要,我将更新更多代码。

Qud*_*dus 7

GetUserIdAsync只接受一个IdentityUser类型。它不接受 的类型ClaimsPrincipal,但GetUserAsync接受。

var user = await _userManager.GetUserAsync(HttpContext.User);
var userId = user.Id;
Run Code Online (Sandbox Code Playgroud)

或者,您也可以从 ClaimsIdentity 获取 Id 声明。

var userId = claimsIdentity.FindFirst("id")?.Value;
Run Code Online (Sandbox Code Playgroud)