我正在研究 Asp.net blazor,我发现了一篇关于 Blazor 托管的文章。
https://docs.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.0
我很想知道从服务器端 Blazor 托管模型切换到客户端和其他方式有多困难?
Chr*_*nty 10
这一点都不难。Robin Sue 已经完成了这项工作,我建议查看他的Blazor Dual mode repo。这是他添加双模式的说明。
创建一个 Blazor(ASP.NET Core 托管)项目,然后更改 .Server 项目的启动类以启用服务器端功能。这不会对客户端 Blazor 产生不利影响,但会启用服务器端服务。为此,您需要services.AddServerSideBlazor();在 ConfigureServices 和endpoints.MapBlazorHub<Client.App>("app"); 在配置
我们现在可以为客户端和服务器端应用程序提供服务,但我们需要默认对客户端中 DI 中提供的 HttpClient 进行 polyfil。服务器端默认不注册它,所以我们检测到这一点,然后在 DI 中注册一个行为类似的 HttpClient 以实现兼容性
// Server Side Blazor doesn't register HttpClient by default
if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
// Setup HttpClient for server side in a client side compatible fashion
services.AddScoped<HttpClient>(s =>
{
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
var uriHelper = s.GetRequiredService<IUriHelper>();
return new HttpClient
{
BaseAddress = new Uri(uriHelper.GetBaseUri())
};
});
}
Run Code Online (Sandbox Code Playgroud)
此时,唯一的区别是我们在浏览器中加载了哪个 blazor JS 文件。这可以通过提供不同的 index.html(我看不到简单的方法)或使用一小段 JS 来决定加载哪个文件来实现
<script id="blazorMode"></script>
<script>
document.getElementById("blazorMode").src = window.location.search.includes("mode=server") ? "_framework/blazor.server.js" : "_framework/blazor.webassembly.js";
</script>
Run Code Online (Sandbox Code Playgroud)
再一次,这一切都是Robin Sue 的作品,完全归功于他。
| 归档时间: |
|
| 查看次数: |
2909 次 |
| 最近记录: |