asp.net-core - 无法从 System.security.claims.claimsPrincipal 转换为 Scheduler.Areas.Identity.Data

标签 asp.net-core model-view-controller controller identity

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

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

var userId = await _userManager.GetUserIdAsync(HttpContext.User);

这是我的 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());
}

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

最佳答案

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

var user = await _userManager.GetUserAsync(HttpContext.User);
var userId = user.Id;

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

var userId = claimsIdentity.FindFirst("id")?.Value;

关于asp.net-core - 无法从 System.security.claims.claimsPrincipal 转换为 Scheduler.Areas.Identity.Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66129286/

相关文章:

html - .NET Core Blazor 应用程序 : How to pass data between pages?

java - Spring MVC - 提交后子实体丢失

asp.net - 尝试使用 Paypal API 时出现错误 500.19

java - 将 MVC 模型与 Swing 应用程序框架结合使用

php - codeigniter 检查每个 Controller 中的用户 session

c# - ASP.NET core 2.2 web api 记录与数据保护 key 相关的警告 : how should we handle this issue?

c# - docker : "npm not found"

ruby-on-rails - 如何使用另一个 Controller 的参数创建 Controller 实例?

testing - Rails 4 参数缺失,Rspec 测试嵌套资源 Controller 更新方法

c# - 如何在 ASP.NET Core Web API 中传递一个 int 数组