Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert from System.security.claims.claimsPrincipal to Scheduler.Areas.Identity.Data

I'm trying to get the current user ID so my Events index page will show events from only current user.

my HttpContext.User has the error "Cannot convert from System.security.claims.claimsPrincipal to Scheduler.Areas.Identity.Data" inside the index of my Events controller.

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

Here is the code in my 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());
}

Where should I be looking to solve this? I'll update with more code if required.

like image 357
elementmg Avatar asked Oct 14 '25 08:10

elementmg


1 Answers

GetUserIdAsync only accepts an IdentityUser type. It doesn't accept a type of ClaimsPrincipal, but GetUserAsync does.

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

Alternatively, you could also get the Id claim from claimsidentity.

var userId = claimsIdentity.FindFirst("id")?.Value;
like image 152
Qudus Avatar answered Oct 19 '25 01:10

Qudus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!