在 Blazor 服务器应用程序中检测服务器预呈现
Detecting server pre-rendering in Blazor server app
有没有什么方法可以通过 OnInitializedAsync
生命周期方法检测 Blazor 组件中正在进行的预渲染?我知道组件工作流会调用 OnInitializedAsync
两次,第一次用于预渲染,第二次用于实际渲染。最后一次性调用OnAfterRenderAsync
方法进行实际渲染。
但是,我需要检测 OnInitializedAsync
中的预渲染。这样我就可以在预渲染中进行一些更改,并在实际渲染中阻止它,反之亦然。
我检查了下面的 GitHub 问题,但没有有效的解决方案。我希望,它应该在 API 中解决,例如 IsPrerendering
。
https://github.com/dotnet/aspnetcore/issues/17282
提前致谢。
没有内置 API,但您可以使用 HTTP 上下文来检测它。
我已经把它包在一个 nuget 包里了
https://www.nuget.org/packages/PreRenderComponent
更新:
从那时起,情况发生了变化,虽然仍然没有 api 检测到这一点,但您应该只在 OnAfterRender/OnAfterRenderAsync 被调用后执行外部调用(如 JSInterop 和 HTTP 调用) .
如果您坚持这种模式,您将永远不需要了解预呈现状态。
检测Blazor服务器预渲染,建议按照官方documentation,引用如下:
Blazor Server apps that prerender their content call OnInitializedAsync twice:
Once when the component is initially rendered statically as part of the page.
A second time when the browser establishes a connection back to the server.
To prevent developer code in OnInitializedAsync from running twice, see the Stateful reconnection after prerendering section.
您可以使用IHttpContextAccessor.HttpContext.Response.HasStarted 属性 来检查应用程序是否是pre-rendering。 HasStarted 指定响应 header 已发送到客户端。如果 HasStarted 设置为 false,则表示应用程序仍在 pre-rendering 并且尚未建立客户端连接。
有没有什么方法可以通过 OnInitializedAsync
生命周期方法检测 Blazor 组件中正在进行的预渲染?我知道组件工作流会调用 OnInitializedAsync
两次,第一次用于预渲染,第二次用于实际渲染。最后一次性调用OnAfterRenderAsync
方法进行实际渲染。
但是,我需要检测 OnInitializedAsync
中的预渲染。这样我就可以在预渲染中进行一些更改,并在实际渲染中阻止它,反之亦然。
我检查了下面的 GitHub 问题,但没有有效的解决方案。我希望,它应该在 API 中解决,例如 IsPrerendering
。
https://github.com/dotnet/aspnetcore/issues/17282
提前致谢。
没有内置 API,但您可以使用 HTTP 上下文来检测它。
我已经把它包在一个 nuget 包里了
https://www.nuget.org/packages/PreRenderComponent
更新:
从那时起,情况发生了变化,虽然仍然没有 api 检测到这一点,但您应该只在 OnAfterRender/OnAfterRenderAsync 被调用后执行外部调用(如 JSInterop 和 HTTP 调用) .
如果您坚持这种模式,您将永远不需要了解预呈现状态。
检测Blazor服务器预渲染,建议按照官方documentation,引用如下:
Blazor Server apps that prerender their content call OnInitializedAsync twice:
Once when the component is initially rendered statically as part of the page.
A second time when the browser establishes a connection back to the server.
To prevent developer code in OnInitializedAsync from running twice, see the Stateful reconnection after prerendering section.
您可以使用IHttpContextAccessor.HttpContext.Response.HasStarted 属性 来检查应用程序是否是pre-rendering。 HasStarted 指定响应 header 已发送到客户端。如果 HasStarted 设置为 false,则表示应用程序仍在 pre-rendering 并且尚未建立客户端连接。