I'm trying to create a ViewComponent for a series of checkboxes based on this article here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2
And this SO answer here: https://stackoverflow.com/a/42853705/2300177
Seems like a perfect case scenario for what I'm trying to do. However, I've created my ViewComponent to include Identity UserManager
to get the 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);
}
}
}
The problem is that when I call this line:
string userId = _userManager.GetUserId(User);
I'm getting an error for User
that reads:
cannot convert from 'System.Security.Principal.IPrincipal' to 'System.Security.Claims.ClaimsPrincipal'
This exact code works in all my controllers and I have no idea where the User
even comes from. Seems like magic, but I'm guessing somewhere inherent inside Identity? Or did I just miss something included in my controllers? (I searched "User" in my controllers and can't link that to anything.)
I'm using the Pomelo MySQL nuget package if that makes a difference? I wouldn't think so.
Anyone know what I'm missing and how to eliminate this error?
Update: Seems it will work with this (at least it gets rid of the error):
string userId = _userManager.GetUserId(Request.HttpContext.User);
Is that the same thing? Is there a using statement I'm missing? Visual studio (2017) usually clues me in to what I'm missing.