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>

 

相关文章:

  • 2021-11-15
  • 2021-05-24
  • 2021-11-07
  • 2021-10-18
  • 2022-02-10
  • 2021-09-12
  • 2021-10-13
  • 2021-05-16
猜你喜欢
  • 2022-01-20
  • 2021-06-25
  • 2022-01-05
  • 2022-02-12
  • 2021-09-14
  • 2021-10-25
  • 2021-05-20
相关资源
相似解决方案