如何在Blazor WASM中实施预渲染

时间:2020-10-31 07:13:07

标签: asp.net blazor blazor-webassembly

带有Prerendering的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();
    }
}

1 个答案:

答案 0 :(得分:3)

客户端

删除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<App>("app"); “ app”不带“#”

服务器端

Pages / _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");
            });
        }
    }
}