繁体   English   中英

ViewComponent 无法识别 AspNetCore.Identity“用户”

[英]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简介

您应该使用ViewComponentUserClaimsPrincipal属性而不是User属性,因此

string userId = _userManager.GetUserId(UserClaimsPrincipal);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM