我有一个使用新的自动渲染模式的 .NET 8 Blazor 项目。我有这个页面,它只是从 gRPC 服务客户端
ForumsService
检索论坛的数据,并在处理请求时显示一个简单的加载屏幕:
@page "/Forum/{ForumPermalink}"
@inject ForumsProto.ForumsProtoClient ForumsService
@rendermode InteractiveAuto
<h3>Forum @@ @ForumPermalink</h3>
@if(_forum is not null)
{
<p>@_forum.Name</p>
}
else
{
<Loading/> @* A simple component with only a p tag *@
}
@code {
[Parameter]
public string ForumPermalink { get; init; } = null!;
private ForumReply? _forum;
protected override async Task OnInitializedAsync()
{
try
{
_forum = await ForumsService.GetForumByPermalinkAsync(new()
{
Permalink = ForumPermalink
});
}
catch(RpcException exception)
{
if(exception.StatusCode == StatusCode.NotFound)
{
NotFoundService.NotifyNotFound();
return;
}
throw;
}
}
}
据我所知,Blazor 自动渲染模式还有一个名为“预渲染”的功能,该功能在任何交互开始之前处理并向客户端发送初始 HTML,以改善初始页面加载体验并且对机器人友好,因此 Google其他机器人可以抓取该网站。
我的问题很简单,就是无法正常工作。当我“查看源代码”页面时,显示的内容如下:
...
<body>
<header>
<--- prerendered correctly -->
</header>
<h3>Forum @ {permalink value is fine}</h3>
<div class="search-overlay" b-5zir38ipii>
...
</div>
<footer b-5zir38ipii>
<--- prerendered correctly -->
</footer>
<script src="/_framework/blazor.web.js"></script>
</body>
</html>
<p>@_forum.Name</p>
和 <Loading/>
组件都不包含在 HTML 中。同样,在普通浏览器中打开该页面时,该页面可以正常工作;但我希望论坛名称(甚至不是加载组件)包含在预渲染中,以便可以按应有的方式对网站进行索引。
所以我的问题是,首先,为什么什么都没有,甚至加载组件也被预渲染了?主要问题是,如何在
OnInitializedAsync()
方法中告诉预渲染器等待论坛,以便页面完全显示给机器人?
这段代码的逻辑要么渲染
_forum.Name
,要么渲染<Loading/>
的内容。它不能做任何其他事情。
@if(_forum is not null)
{
<p>@_forum.Name</p>
}
else
{
<Loading/> @* A simple component with only a p tag *@
}
因此,要么
<Loading/>
不渲染任何内容 [您说这不是真的],要么 @_forum.Name
为 null 或为空 [在这种情况下您应该看到 <p></p>
]。
断言这一点:
@if(_forum is not null)
{
<div>Forum us not nothing</div>
<p>@_forum.Name</p>
}
else
{
<div>Forum is nothing</div>
<Loading/> @* A simple component with only a p tag *@
}