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

Ayo*_*aye 2 c# asp.net-core asp.net-core-webapi

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

当前用户服务:

public interface ICurrentUserService
{
    public string UserId { get; }
    public string UserName { get; }
    bool IsAuthenticated { get; }
    public string IpAddress { get; }
}
Run Code Online (Sandbox Code Playgroud)

当前用户服务:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();
Run Code Online (Sandbox Code Playgroud)

但是当我尝试运行该应用程序时,出现以下错误:

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'.
Run Code Online (Sandbox Code Playgroud)
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'.
Run Code Online (Sandbox Code Playgroud)

是15号线

我该如何解决这个问题?

谢谢。

Yon*_*hun 5

注册HttpContextAccessor依赖。

builder.Services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)
builder.Services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)

参考

从自定义组件中使用 HttpContext