首页 > 解决方案 > 未处理的异常呈现组件:在“窗口”中找不到“AuthenticationService”

问题描述

如果用户尝试访问授权页面,我想将未经授权的用户重定向到登录页面。到目前为止,我使用教程编写了这个。项目建设成功。但是浏览器抛出了这个错误

未处理的异常呈现组件:在“窗口”中找不到“AuthenticationService”

页面停留在授权上

<Authorizing>
  <div class="main">Please wait...</div>
</Authorizing>

所有页面都打印“请稍候...”我该如何解决这个错误?

应用剃须刀

<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                <RedirectToLogin />
            </NotAuthorized>
            <Authorizing>
                <div class="main">Please wait...</div>
            </Authorizing>
        </AuthorizeRouteView>
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

_Imports.Razor

@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using Kermes.Client
@using Kermes.Client.Shared
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Blazorise

程序.cs

public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.Services
                  .AddBlazorise(options =>
                  {
                      options.ChangeTextOnKeyPress = true;
                  })
                  .AddBootstrapProviders()
                  .AddFontAwesomeIcons();
            builder.Services.AddSingleton(new HttpClient
            {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });
            builder.RootComponents.Add<App>("app");
            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            builder.Services.AddApiAuthorization(options => {
                options.AuthenticationPaths.LogInPath = "auth/login";
                options.AuthenticationPaths.LogInCallbackPath = "auth/login-callback";
                options.AuthenticationPaths.LogInFailedPath = "auth/login-failed";
                options.AuthenticationPaths.LogOutPath = "auth/logout";
                options.AuthenticationPaths.LogOutCallbackPath = "auth/logout-callback";
                options.AuthenticationPaths.LogOutFailedPath = "auth/logout-failed";
                options.AuthenticationPaths.LogOutSucceededPath = "auth/logged-out";
                options.AuthenticationPaths.ProfilePath = "auth/profile";
                options.AuthenticationPaths.RegisterPath = "auth/register";
            });

            var host = builder.Build();
            host.Services
              .UseBootstrapProviders()
              .UseFontAwesomeIcons();

            await host.RunAsync();
        }
    }

计数器.cs

@page "/counter"
@attribute [Authorize]
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

服务器/启动.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using KermesAPI.Helpers;
using KermesAPI.Services;
using AutoMapper;
using System;

namespace Kermes.Server
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>();
            services.AddAuthentication();
            services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.IgnoreNullValues = true);
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddSwaggerGen();

            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddScoped<IAccountService, AccountService>();
            services.AddScoped<IEmailService, EmailService>();
            services.AddControllersWithViews();
            services.AddRazorPages();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}

标签: c#blazor

解决方案


试试这个:

<script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>

我有同样的问题。在 Blazor 客户端项目的 index.html 文件中添加上面的 Script-Reference 为我修复了它。


推荐阅读