c# - ASP.NET Core Web API - 尝试激活 'IHttpContextAccessor' 时无法解析类型 'Services.CurrentUserService' 的服务

标签 c# asp.net-core asp.net-core-webapi

我正在 ASP.NET Core-6 Web API 用户身份验证登录中实现 CurrentUser 服务。我正在使用 IdentityDbContext:

ICurrentUserService:

public interface ICurrentUserService
{
    public string UserId { get; }
    public string UserName { get; }
    bool IsAuthenticated { get; }
    public string IpAddress { get; }
}

当前用户服务:

using Microsoft.AspNetCore.Http;
using System.Security.Claims;

public class CurrentUserService : ICurrentUserService
{
    public string UserId { get; }
    public string UserName { get; }
    public bool IsAuthenticated { get; }
    public string IpAddress { get; }

    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        IpAddress = httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress.ToString();
        UserName = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
        UserId = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
        IsAuthenticated = UserId != null;
    }
}

然后在 Program.cs 中我有这个:

var builder = WebApplication.CreateBuilder(args);

// Register CurrentUserService
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

var app = builder.Build();

但是当我尝试运行该应用程序时,我收到此错误:

System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Services.ICurrentUserService Lifetime: Scoped ImplementationType: Services.CurrentUserService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<Main>$(String[] args) in C:\MyApp\WebApi\Program.cs:line 15

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: Services.ICurrentUserService Lifetime: Scoped ImplementationType: Services.CurrentUserService': Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'Services.CurrentUserService'.
var app = builder.Build()

是第 15 行

如何解决这个问题?

谢谢。

最佳答案

注册HttpContextAccessor依赖项。

builder.Services.AddHttpContextAccessor();
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpContextAccessor();

// Register CurrentUserService
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

var app = builder.Build();

引用文献

Use HttpContext from custom components

关于c# - ASP.NET Core Web API - 尝试激活 'IHttpContextAccessor' 时无法解析类型 'Services.CurrentUserService' 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72172369/

相关文章:

c# - 如何自动化定期执行作业的 WCF 服务

javascript - 如何在 JQuery 中制作通用切换功能?

azure-active-directory - 如何通过 Azure 数据库和 Active Directory 密码身份验证在 ASP.NET Core 中使用 Hangfire

c# - Serilog 不使用 Serilog.Sinks.MssqlServer 将日志写入 SQL Server

c# - 如何从 Controller 方法访问 token 数据?

c# - 这个傅立叶变换实现有什么问题

javascript - Ajax 未将数组传递给 Controller ​​操作?

c# - 找不到方法 : 'System.Collections.Generic.IList` 1<Nop. Services.Cms.IWidgetPlugin>

asp.net - 在 ASP.NET Core 中作为 ConfigurationSection 类的参数传递什么

c# - 控制流从模型返回而不进入 Controller 操作