[尝试从此处实施答案时>How to get the current logged in user Id in ASP.NET Core并且用户将我重定向到此处> https://github.com/dotnet/aspnetcore/issues/18348
var UserId = User.FindFirstValue(ClaimTypes.Name);
^这不起作用,并显示以下错误'User' does not contain a definition for 'FindFirstValue'
我的控制器正在调用的完整代码段...
using Microsoft.EntityFrameworkCore;
using ProjectName.Data;
using ProjectName.Repo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Web;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using System.Web.Providers.Entities;
namespace ProjectName.Processing
{
public class ControllerNameProcessing
{
private readonly ProjName_DevelContext _context = new ProjName_DevelContext();
private async Task<List<2ndClassNameRepository>> GetNameFromRepo()
{
List<2ndClassNameRepository> repoList = new List<2ndClassNameRepository>();
var Temp = await _context.tablename.ToListAsync();
/* Working Test
2ndClassNameRepository repo = new 2ndClassNameRepository();
repo.UserName = "JohnDoe";
repoList.Add(repo);
return repoList;
*/
2ndClassNameRepository repo = new 2ndClassNameRepository();
// repo.UserName = "JohnDoe";
var userId = User.FindFirstValue(ClaimTypes.Name);
repo.UserName = userId;
repoList.Add(repo);
return repoList;
}
internal async Task<List<2ndClassNameRepository>> GetUserName()
{
return await GetNameFromRepo();
}
}
}
知道为什么会出现此错误吗?
尝试如下获取用户ID
var userId = User.Claims.Where(c => c.Type == "sub").FirstOrDefault().Value;
好!遇到问题了。User
ClaimPrinciple
仅在Controller
上下文中可用。我看到您的ControllerNameProcessing
不是Controller
类。因此,您应该执行以下操作:
public class ControllerNameProcessing
{
private readonly IHttpContextAccessor _httpContextAccessor;
public ControllerNameProcessing(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private async Task<List<2ndClassNameRepository>> GetNameFromRepo()
{
// Omitted your other codes for brevity
var userName = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.Name);
// Omitted your other codes for brevity
}
}
然后您应按以下步骤在IHttpContextAccessor
类中注册Startup
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}