【问题标题】:How to implement pre-rendering in Blazor WASM如何在 Blazor WASM 中实现预渲染
【发布时间】:2021-02-13 13:30:06
【问题描述】:

具有预渲染功能的 Blazor WASM 在单击登录链接时出错。

我在 Startup.cs 中添加了以下内容:

    services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
    services.AddScoped<SignOutSessionStateManager>();

https://github.com/jonasarcangel/PrerenderWithAuth/blob/master/PrerenderWithAuth/Server/Startup.cs

这是在https://github.com/dotnet/aspnetcore/issues/15253 中提出的。其他更改也取自 https://jonhilton.net/blazor-wasm-prerendering/

这是错误:

System.InvalidCastException:无法转换类型的对象 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' 输入 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IRemoteAuthenticationService`1[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState]'。

更新:我正在尝试这个,但我不知道在每个实现中放置什么。

public class HybridAuthenticationStateProvider : ServerAuthenticationStateProvider, IRemoteAuthenticationService<RemoteAuthenticationState>
{
    public async Task<RemoteAuthenticationResult<RemoteAuthenticationState>> CompleteSignInAsync(RemoteAuthenticationContext<RemoteAuthenticationState> context)
    {
        throw new NotImplementedException();
    }

    public async Task<RemoteAuthenticationResult<RemoteAuthenticationState>> CompleteSignOutAsync(RemoteAuthenticationContext<RemoteAuthenticationState> context)
    {
        throw new NotImplementedException();
    }

    public async Task<RemoteAuthenticationResult<RemoteAuthenticationState>> SignInAsync(RemoteAuthenticationContext<RemoteAuthenticationState> context)
    {
        throw new NotImplementedException();
    }

    public async Task<RemoteAuthenticationResult<RemoteAuthenticationState>> SignOutAsync(RemoteAuthenticationContext<RemoteAuthenticationState> context)
    {
        throw new NotImplementedException();
    }
}

【问题讨论】:

  • ServerAuthenticationStateProvider 不是用于服务器端 Blazor - 它位于服务器命名空间中 - 为什么要在 Blazor WebAssembly 中使用它?
  • 我正在遵循这里提到的建议:github.com/dotnet/aspnetcore/issues/15253
  • 哦,我看我没有发现预渲染,所以你包含的代码在主机启动中?该问题表明您在预呈现(在服务器上需要服务器身份验证)和客户端交互时(需要远程身份验证)时需要为身份验证注册不同的服务 - 该错误表明您没有涵盖这两种情况跨度>
  • 我正在创建一个 HybridAuthenticationStateProvider 类,但我不知道在每个实现中放置什么。
  • @Jonas Arcangel,你在做什么......这个错误只证明你的代码有问题,它可能根本与 ServerAuthenticationStateProvider 无关。我认为这个对象没有问题。我运行了你的代码,得到了 505 错误,所以我要创建一个新的应用示例。

标签: asp.net blazor blazor-webassembly


【解决方案1】:

客户端

删除 wwwroot/index.html 文件

Program.Main

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddHttpClient("PrerenderWithAuth.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

            // Supply HttpClient instances that include access tokens when making requests to the server project
            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("PrerenderWithAuth.ServerAPI"));

            builder.Services.AddApiAuthorization();

            await builder.Build().RunAsync();
        }

请注意:builder.RootComponents.Add&lt;App&gt;("app"); “app”没有'#'

服务器端

页面/_Host.cshtml

@page "/"

@namespace PrerenderWithAuth.Server.Pages

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>PrerenderWithAuth</title>
    <base href="~/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link href="PrerenderWithAuth.Client.styles.css" rel="stylesheet" />
</head>

<body>
    @*<div id="app">Loading...</div>*@

    <app>
        @if (!HttpContext.Request.Path.StartsWithSegments("/authentication"))
        {
            <component type="typeof(PrerenderWithAuth.Client.App)" render-mode="Static" />
            
        }
        else
        {
            <text>Loading...</text>
            
        }
    </app>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">?</a>
    </div>
    <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
    <script src="_framework/blazor.webassembly.js"></script>
</body>

</html>

PrerenderWithAuth.Server/_Imports.razor

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using PrerenderWithAuth
@using PrerenderWithAuth.Shared

启动类:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PrerenderWithAuth.Server.Data;
using PrerenderWithAuth.Server.Models;
using System.Linq;

namespace PrerenderWithAuth.Server
{
    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.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Added by me
            services.Configure<RazorPagesOptions>(options => options.RootDirectory = "/Pages");
            // Added by me
            services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();
            // Added by me
            services.AddScoped<SignOutSessionStateManager>();

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();

           
        }

        // 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();
                app.UseMigrationsEndPoint();
                app.UseWebAssemblyDebugging();
            }
            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.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();



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

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

                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

【讨论】:

  • 是的,它奏效了。关键修复在 _Host.html 中。使用条件和静态渲染模式有效。 jonhilton.net/blazor-wasm-prerendering 中使用 WebAssemblyPrerendered 的指令没有。
猜你喜欢
  • 1970-01-01
  • 2021-02-25
  • 2021-03-02
  • 2019-09-29
  • 2022-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
相关资源
最近更新 更多