简体   繁体   English

ASP.NET Core 3.1“‘用户’不包含‘FindFirstValue’的定义”

[英]ASP.NET Core 3.1 "'User' does not contain a definition for 'FindFirstValue'"

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在尝试从此处执行答案时> 如何在 ASP.NET 核心中获取当前登录的用户 ID,并且用户将我重定向到此处> https://github.com/dotnet/aspnetcore/issues/18348

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

^ This is not working, and prints the following error 'User' does not contain a definition for 'FindFirstValue' ^ 这不起作用,并打印以下错误'User' does not contain a definition for 'FindFirstValue'

Edit: Adding controller snippet编辑:添加 controller 片段

The full snippet of my controller...我的 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...我的 controller 正在调用的完整片段...

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();
        }
    }
}

Any idea why I'm getting this error?知道为什么我会收到此错误吗?

Try to get user id as follow (for User of type ClaimsPrincipal)尝试按如下方式获取用户 ID(对于 ClaimsPrincipal 类型的用户)

 var userId = User.Claims.Where(c => c.Type == "sub").FirstOrDefault().Value;

And For User of type System.Web.Providers.Entities.User use对于 System.Web.Providers.Entities.User 类型的用户使用

User.UserId

https://docs.microsoft.com/en-us/previous-versions/aspnet/dn253175(v=vs.108) https://docs.microsoft.com/en-us/previous-versions/aspnet/dn253175(v=vs.108)

Okay.好的。 Got the problem.有问题。 User ClaimPrinciple is only available in the Controller context. User ClaimPrinciple仅在Controller上下文中可用。 I see your ControllerNameProcessing is not a Controller class.我看到您的ControllerNameProcessing不是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
     }
}

Then you should register IHttpContextAccessor in the Startup class as follows:然后你应该在Startup class 中注册IHttpContextAccessor如下:

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

Now in your controller:现在在您的 controller 中:

[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);
    }
}

Then you should register OtherClassNameProcessing in the Startup class as follows:然后你应该在Startup class 中注册OtherClassNameProcessing如下:

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

The issue you are likely having is that you lack the right package.您可能遇到的问题是您缺少正确的 package。

Install this: Microsoft.Extensions.Identity.Core安装这个:Microsoft.Extensions.Identity.Core

Then it should start working once the using statement is included.然后它应该在包含 using 语句后开始工作。

暂无
暂无

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

相关问题 “对象”不包含定义<property>在asp.net核心3.1中 - 'object' does not contain a definition for <property> in asp.net core 3.1 ASP.NET Core:IConfigurationBuilder 不包含 AddAzureKeyVault 的定义 - ASP.NET Core: IConfigurationBuilder Does Not Contain Definition For AddAzureKeyVault 带有 MVC iapplicationbuilder 的 ASP.NET Core 不包含 usemvc 的定义 - ASP.NET Core with MVC iapplicationbuilder does not contain a definition for usemvc ASP.NET MVC Core 6 中的 User.FindFirstValue(ClaimTypes.Email) 使用 VS 2022 返回 Null - User.FindFirstValue(ClaimTypes.Email) in ASP.NET MVC Core 6 using VS 2022 returns Null .net core 3.1 Blazor WebAssembly:不包含“LoginMode”的定义 - .net core 3.1 Blazor WebAssembly: does not contain a definition for "LoginMode" ASP.NET Core API 获取错误:&#39;EntityEntry<Vehicle> &#39; 不包含定义 - ASP.NET Core API Get error: 'EntityEntry<Vehicle>' does not contain a definition “IServiceCollection”不包含“AddAWSService”的定义,并且在asp.net core 2.2 中没有可访问的扩展方法“AddAWSService”错误? - 'IServiceCollection' does not contain a definition for 'AddAWSService' and no accessible extension method 'AddAWSService' error in asp.net core 2.2? int不包含Getawaiter + asp.net核心Web api异步的定义 - int does not contain a definition for Getawaiter + asp.net core web api async DbContextOptionsBuilder&#39;不包含&#39;usesqlserver&#39;的定义并且在asp.net core 2.2中没有扩展方法&#39;usesqlserver&#39;? - DbContextOptionsBuilder' does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver' in asp.net core 2.2? ASP.NET 内核 - 如何解决“ICollection”<approvalattachment> ' 不包含 'FilePath' 的定义并且没有可访问的扩展方法</approvalattachment> - ASP.NET Core - How to resolve 'ICollection<ApprovalAttachment>' does not contain a definition for 'FilePath' and no accessible extension method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM