深入浅出Blazor webassembly之以SubDirectory方式部署

blazor wasm 默认开发环境url 为, http://localhost:5000

生产环境多数情况下需要在端口后增加一个名称, 这样能直观知道这个url是属于哪个系统的. 比如 http://localhost:5000/CoolApp

url要增加这个应用名, 自然不应手工改写所有 razor page 的url, 那样就太麻烦了, 也不适合工程化需要. blazor wasm应用本身内置支持这一需求.

 

====================================

非subdirectory部署的配置

====================================

1. index.html head 下 base tag 为

    <base href="/" />

   这个base tag对于 SPA 框架都很有用, 比如 Angular 框架, 也使用 base tag.

2 服务启动命令为,

   dotnet run --project "c:\blazorapps\demo1\demo1.csproj"

3. 浏览器访问地址为 http://localhost:5000

 

====================================

以subdirectory部署的配置

====================================

假设应用名定为 CoolApp, 下面步骤可以将 CoolApp 加到 url中

1. index.html head 下 base tag 为

    <base href="CoolApp/" />

   用于 razor路由计算, 以及设定 blazor.webassembly.js 的访问地址

2 服务启动命令为,

   dotnet run --project "c:\blazorapps\demo1\demo1.csproj" --pathbase="/CoolApp"

用于控制css静态资源的base 路径

3. 浏览器访问地址为 http://localhost:5000/CoolApp

 注意 base tag 和 浏览器url都是大小写敏感的, 而启动命令 pathbase 大小写不敏感

 

 

====================================

同时适应本地的根目录部署和生成环境的 subDirectory 部署形式

====================================

摘自 https://blog.elmah.io/how-to-fix-blazor-wasm-base-path-problems/

index.html 文件中, 用下面代码替换掉原来的 <base href="/" /> , 实现原理是:

通过 js 根据浏览器 url动态调整 base tag.

<base />
<script>
    var path = window.location.pathname.split('/');
    var base = document.getElementsByTagName('base')[0];
    if (window.location.host.includes('localhost')) {
        base.setAttribute('href', '/');
    } else if (path.length > 2) {
        base.setAttribute('href', '/' + path[1] + '/');
    } else if (path[path.length - 1].length != 0) {
        window.location.replace(window.location.origin + window.location.pathname + '/' + window.location.search);
    }
</script>

 

posted @ 2021-09-19 19:41  harrychinese  阅读(268)  评论(0编辑  收藏  举报