gpt4 book ai didi

asp.net - 如何在 Blazor WASM 中实现预渲染

转载 作者:行者123 更新时间:2023-12-04 16:25:45 26 4
gpt4 key购买 nike

具有预渲染功能的 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: Unable to cast object of type'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider'to type'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();
}
}

最佳答案

客户端

删除 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”没有'#'

服务器端

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

关于asp.net - 如何在 Blazor WASM 中实现预渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64619333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com