我有一个 Blazor 版本 6/7 服务器应用程序,需要将其转换为版本 8 InteractiveServer。我这里有防伪代码,也需要更改。
我需要做出哪些改变?
获取 App.razor 的内容,删除外部
<CascadingAuthenticationState>
并将其粘贴为新创建的 Routes.razor 的内容。然后将 AppAssembly="@typeof(App).Assembly"
更改为 AppAssembly="@typeof(Program).Assembly"
。
旧应用程序.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<div class="message--401">
<h1 role="alert">Sorry, you're not authorized to view this page.</h1>
<p>You must have an Admin claim and be set to use 2FA when logging in.</p>
</div>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<div class="message--404">
<h1 role="alert">Sorry, there's nothing at this address.</h1>
</div>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
新路线.razor
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<div class="message--401">
<h1 role="alert">Sorry, you're not authorized to view this page.</h1>
<p>You must have an Admin claim and be set to use 2FA when logging in.</p>
</div>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<div class="message--404">
<h1 role="alert">Sorry, there's nothing at this address.</h1>
</div>
</LayoutView>
</NotFound>
</Router>
在 Program.cs 中,替换:
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor(options => { options.DetailedErrors = debugMode; });
与:
builder.Services.AddRazorComponents().AddInteractiveServerComponents(options => { options.DetailedErrors = debugMode; });
builder.Services.AddCascadingAuthenticationState();
并替换(在 UseAuthentication(); UseAuthorization(); 之后):
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
与:
app.UseAntiforgery();
app.MapRazorPages();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
最后,将 _Host.cshtml 复制到 App.razor,然后删除 _Host.cshtml。执行此操作时,删除 App.razor.cs 和 _Host.cshtml 中 xsrf 周围的代码 - 现在这一切都由调用
app.UseAntiforgery()
处理。
我不会在下面列出所有内容,因为少数更改会在未更改的内容中丢失。下面是变化的内容。请密切关注
<base>
,因为这是一个微妙但关键的变化!
更改 _Host.cshtml 中的源:
<head>
<base href="~/" />
<component type="typeof(HeadOutlet)" render-mode="Server" />
</head>
<body>
<component type="typeof(App)" render-mode="Server" param-InitialState="initialTokenState" />
</body>
到新的(覆盖旧内容)App.razor:
<head>
<base href="/" />
<HeadOutlet @rendermode="InteractiveServer" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
</body>