如何获取 Blazor 用于我的组件的渲染模式。 有这个建议,但这对汽车也不起作用。我想验证我是否已正确配置所有内容,以便我的应用程序在 InteractiveServer 中进行调整。
您可以尝试在 Blazor WebApp 模板自动全局项目中执行以下操作:
在客户端项目中安装
Microsoft.AspNetCore.Http 2.2.2
。然后您可以通过 CascadingParameter 或 IHttpContext Accessor 访问 HttpContext。他们有一些区别。
1.级联参数
修改 Home.razor 如下
@page "/"
@using System.Runtime.InteropServices
@using Microsoft.AspNetCore.Http
@rendermode InteractiveAuto
@render_mode
@code {
private string? render_mode;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
protected override void OnInitialized()
{
if (HttpContext != null)
{
render_mode = "prerender";
}
else
{
if (RuntimeInformation.ProcessArchitecture != Architecture.Wasm)
{
render_mode = "server"; //the architecture could be x64 depending on your machine.
}
if (RuntimeInformation.ProcessArchitecture == Architecture.Wasm)
{
render_mode = "wasm";
}
}
}
}
然后,当运行项目时,您将看到“render_mode”从“prerender”更改为“Server”。过了一会儿,当wasm下载完成并再次刷新页面时,您将看到它从“prerender”更改为“wasm” 。因为这是文档说使用级联方式访问httpcontext。 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0#ihttpcontextaccessorhttpcontext-in-razor-components-blazor
对于交互式渲染,该值始终为空。 所以我们用“HttpContext != null”来判断是否是预渲染。
2.IHttpContextAccessor
正如文档所说,在 blazor 中不建议这样做。但我认为应该明确的是,如果使用 IhttpcontextAccessor.HttpContext,“prerender”或“InteractiveServicer”都会获胜
没有 null Httpcontext。您需要使用
HttpContext.Response.HasStarted
builder.Services.AddHttpContextAccessor();
添加到服务器和客户端项目,然后修改 Home.razor,如下所示。
@page "/"
@using System.Runtime.InteropServices
@using Microsoft.AspNetCore.Http
@rendermode InteractiveAuto
@inject IHttpContextAccessor _httpContextAccessor
@render_mode
@code {
private string? render_mode;
protected override void OnInitialized()
{
if (_httpContextAccessor.HttpContext != null)
{
if (!_httpContextAccessor.HttpContext.Response.HasStarted)
{
render_mode = "prerender";
}
else
{
render_mode = "server";
}
}
else
{
render_mode = "wasm";
}
}
}
那么以上2种方式的测试结果是一样的。