简体   繁体   English

“Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler”类型没有服务错误

[英]No service for type ' Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler' Error

I am currently working on a project that consists of sub-projects such as WebApp, API, and Client class library.我目前正在开发一个由 WebApp、API 和 Client class 库等子项目组成的项目。 (The project structure is shown below). (项目结构如下图)。 Project Solution Structure项目解决方案结构

Although the project is a web-based project, it uses windows Identity as authentication identity since it is an internal application.虽然该项目是一个基于 Web 的项目,但它使用 windows 身份作为身份验证身份,因为它是一个内部应用程序。 I implemented the authorization policy of the WebApp project without any problems by following the steps in the implementation_link .我按照 implementation_link 中的步骤实现了 WebApp 项目的授权策略,没有任何问题。 Now I can control access using DataAnnotation in WebApp (ex. [Authorize(Roles = "Admin"]). If I add Authorization control on the API side, WebApp cannot access this API. This is because of HttpContext.User is null. I found the solution to this problem solution_link . I adapted this solution to the project as below:现在我可以在 WebApp 中使用 DataAnnotation 控制访问(例如 [Authorize(Roles = "Admin"])。如果我在 API 端添加授权控制,WebApp 无法访问此 API。这是因为 HttpContext.User 为 Z37A6275ECC68C207A6289ECC64C07A6789ECC64C07A6789ECC08C找到了这个问题的解决方案 solution_link 。我将此解决方案应用于项目,如下所示:

ServiceCollectionExtensions.cs in WebApp project: WebApp 项目中的 ServiceCollectionExtensions.cs:

public static IServiceCollection AddAuraServices(this IServiceCollection serviceCollection, IConfiguration configuration)
    {
        serviceCollection.AddTransient<IModelDatabaseNamesProvider, StandardCasingModelDatabasesNamesProvider>();
        serviceCollection.Configure<RouteOptions>(routeOptions =>
        {
            routeOptions.ConstraintMap.Add(ModelDatabasesNameConstraint.Name, typeof(ModelDatabasesNameConstraint));
        });
        serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        serviceCollection.AddScoped<IModelMetadataProvider>(serviceProvider =>
        {
            var httpContext = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
            var modelName = httpContext.Request.RouteValues["model-name"].ToString();
            return new ModelMetadataProvider(modelName);
        });

        DateOnlyTypeConverter.AddAttributeToType();

        serviceCollection.AddHttpClient<UploadRulesClient>("ServerAPI", (httpClient) =>
        {
            httpClient.BaseAddress = new Uri(configuration["AuraApiClient:BaseAddress"]);
        }).AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

        serviceCollection.AddHttpClient<ScenarioZipFilesClient>("ServerAPI",(httpClient) =>
        {
            httpClient.BaseAddress = new Uri(configuration["AuraApiClient:BaseAddress"]);
        }).AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

        serviceCollection.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
            .CreateClient("ServerAPI"));


        var jsonSerializerOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };

        ClientJsonResponse.Configure(jsonSerializerOptions);
        serviceCollection.AddSingleton(jsonSerializerOptions);
        serviceCollection.AddAuraDropzoneConfig(configuration);
        return serviceCollection;
    }

Startup.cs of WebApp: WebApp 的 Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
        services.AddAuthorization();

        services.AddControllersWithViews();
        //services.AddRazorPages();
        services.AddAuraServices(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        //app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "model-database", pattern: "{model-name:modeldatabasename}/{controller=ZipFiles}/{action=Index}/{id?}");
            endpoints.MapControllerRoute(name: "default", pattern: "", new { controller = "Home", action = "Index" });
            //endpoints.MapRazorPages();
        });
    }
}

But this time I am getting No service for Type Error .但是这次我没有为 Type Error提供服务。 How can I solve this problem?我怎么解决这个问题? Where do you think I am going wrong?你觉得我哪里错了? Thanks谢谢

You have to register BaseAddressAuthorizationMessageHandler :您必须注册BaseAddressAuthorizationMessageHandler

serviceCollection.AddTransient<BaseAddressAuthorizationMessageHandler>();

Thank you for your comment but it didn't work.感谢您的评论,但没有奏效。 I tried this code line into either ServiceCollectionExtension.cs file and Startup.cs but the result is the same.我在 ServiceCollectionExtension.cs 文件和 Startup.cs 中尝试了此代码行,但结果是相同的。 I got this error:我收到了这个错误:

System.AggregateException HResult=0x80131500 Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler': Unable to resolve service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' while attempting to activate 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler'.) 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 System.AggregateException HResult=0x80131500 消息=无法构造某些服务(验证服务描述符时出错'ServiceType: Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Components.WebAssembly。 Authentication.BaseAddressAuthorizationMessageHandler':尝试激活“Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler”时,无法解析“Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider”类型的服务。)Source=Microsoft.Extensions.DependencyInjection StackTrace:在 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 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 Aura.App.Program.Main(String[] args) in C:\Users\DRA11KS\source\repos\AuRA\Aura.App\Program.cs:line 16 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) 在 Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider() 在 Microsoft.Extensions。 Hosting.HostBuilder.Build() at Aura.App.Program.Main(String[] args) in C:\Users\DRA11KS\source\repos\AuRA\Aura.App\Program.cs:line 16

This exception was originally thrown at this call stack: Inner Exception 1: InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler Lifetime: Transient ImplementationType: Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler': Unable to resolve service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' while attempting to activate 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler'.此异常最初是在此调用堆栈中引发的:内部异常 1:InvalidOperationException:验证服务描述符时出错'ServiceType:Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler Lifetime:Transient ImplementationType:Microsoft.AspNetCore.Components.WebAssembly.Authentication .BaseAddressAuthorizationMessageHandler':尝试激活“Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler”时,无法解析“Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider”类型的服务。 Inner Exception 2: InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider' while attempting to activate 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler'.内部异常 2:InvalidOperationException:尝试激活“Microsoft.AspNetCore.Components.WebAssembly.Authentication.BaseAddressAuthorizationMessageHandler”时,无法解析“Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider”类型的服务。

How can I solve it?我该如何解决? Thanks.谢谢。

暂无
暂无

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

相关问题 命名空间名称身份验证在命名空间 Microsoft.AspNetCore.Components.WebAssembly.Authentication 中不存在 - Namespace name Authentication does not exist in the namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication 没有“Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider”类型的注册服务 - There is no registered service of type 'Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider' 没有针对类型“Microsoft.AspNetCore.Identity.RoleManager 错误的服务” - No service for type 'Microsoft.AspNetCore.Identity.RoleManager error C# Blazor WebAssembly:参数 2:无法从“void”转换为“Microsoft.AspNetCore.Components.EventCallback” - C# Blazor WebAssembly: Argument 2: cannot convert from 'void' to 'Microsoft.AspNetCore.Components.EventCallback' 没有注册“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered InvalidOperationException:无法解析类型为&#39;Microsoft.AspNetCore.Identity.RoleManage的服务 - InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManage 无法解析 Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine 类型的服务 - Unable to resolve service for type Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine 无法解析类型为“Microsoft.AspNetCore.Identity.IRoleStore”的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore Blazor无法解析类型为&#39;Microsoft.AspNetCore.Http.IHttpContextAccessor&#39;的服务? - Blazor cannot resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'? 没有注册类型为“Microsoft.AspNetCore.Mvc ...”的服务 - No service for type 'Microsoft.AspNetCore.Mvc..." has been registered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM