ASP.NET Core 3.1“用户”不包含“ FindFirstValue”的定义。 [英] ASP.NET Core 3.1 "'User' does not contain a definition for 'FindFirstValue'"

查看:384
本文介绍了ASP.NET Core 3.1“用户”不包含“ FindFirstValue”的定义。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从此处实施答案时> 如何在ASP.NET Core中获取当前登录的用户ID
,然后用户将我重定向到此处> > https://github.com/dotnet/aspnetcore/issues/18348

While trying to implement the answer from here > How to get the current logged in user Id in ASP.NET Core and the user redirected me to here > https://github.com/dotnet/aspnetcore/issues/18348

var UserId = User.FindFirstValue(ClaimTypes.Name);

^工作,并显示以下错误用户不包含 FindFirstValue的定义

^ This is not working, and prints the following error 'User' does not contain a definition for 'FindFirstValue'

编辑:添加控制器代码段

我的控制器的完整代码段...

The full snippet of my controller...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectName.Processing;
using ProjectName.Repository;
using Newtonsoft.Json;

namespace ProjectName.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ClassNameController : ControllerBase
    {
        private readonly ILogger<ClassNameController> _logger;
        private OtherClassNameProcessing proc = new OtherClassNameProcessing();

        public ClassNameController(ILogger<ClassNameController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [ProducesResponseType(typeof(List<2ndOtherClassNameRepository>), StatusCodes.Status200OK)]
        public IActionResult GetUserName()
        {
            var data = proc.GetUserName();
            return Ok(data.Result);
        }
    }
}

我的控制器的完整代码段是调用...

The full snippet my controller is calling...

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 OtherClassNameProcessing
    {
        private readonly ProjName_DevelContext _context = new ProjName_DevelContext();
        private async Task<List<2ndOtherClassNameRepository>> GetNameFromRepo()
        {
            List<2ndOtherClassNameRepository> repoList = new List<2ndOtherClassNameRepository>();
            var Temp = await _context.tablename.ToListAsync();
            /* Working Test
            2ndOtherClassNameRepository repo = new 2ndOtherClassNameRepository();
            repo.UserName = "JohnDoe";
            repoList.Add(repo);
            return repoList;
            */
            2ndOtherClassNameRepository repo = new 2ndOtherClassNameRepository();
            // repo.UserName = "JohnDoe";
            var userId = User.FindFirstValue(ClaimTypes.Name);
            repo.UserName = userId;
            repoList.Add(repo);
            return repoList;
        }
        internal async Task<List<2ndOtherClassNameRepository>> GetUserName()
        {
            return await GetNameFromRepo();
        }
    }
}

任何人知道我为什么

推荐答案

好!遇到问题了。 User ClaimPrinciple 仅在 Controller 上下文中可用。我看到您的 ControllerNameProcessing 不是 Controller 类。因此,您应该执行以下操作:

Okay! Got the problem. User ClaimPrinciple is only available in the Controller context. I see your ControllerNameProcessing is not a Controller class. So you should do as follows:

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
     }
}

然后,应在 Startup 类中注册 IHttpContextAccessor ,如下所示:

Then you should register IHttpContextAccessor in the Startup class as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
}

现在在您的控制器中:

[ApiController]
[Route("api/[controller]/[action]")]
public class ClassNameController : ControllerBase
{
    private readonly ILogger<ClassNameController> _logger;
    private OtherClassNameProcessing _otherClassNameProcessing;

    public ClassNameController(ILogger<ClassNameController> logger, OtherClassNameProcessing otherClassNameProcessing)
    {
        _logger = logger;
        _otherClassNameProcessing = otherClassNameProcessing;
    }

    [HttpGet]
    [ProducesResponseType(typeof(List<2ndOtherClassNameRepository>), StatusCodes.Status200OK)]
    public IActionResult GetUserName()
    {
        var data = proc.GetUserName();
        return Ok(data.Result);
    }
}

然后您应该注册 OtherClassNameProcessing Startup 类中,如下所示:

Then you should register OtherClassNameProcessing in the Startup class as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddScoped<OtherClassNameProcessing>();
}

这篇关于ASP.NET Core 3.1“用户”不包含“ FindFirstValue”的定义。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆