使用Github Pages托管Blazor應用


1.環境

VS2019 16.5.1

.NET Core SDK 3.1.200

Blazor WebAssembly Templates 3.2.0-preview2.20160.5 

2.簡介

每個Github用戶都可以擁有一個Github Pages,可以用來作為個人網站或者是用來作為項目的demo、文檔等。本文將介紹如何將一個balzor應用(WASM)部署到Github Pages上。

3.流程

3.1.創建Github Pages

首先登錄Github,然后創建一個倉庫userName.github.io,其中userName是github的用戶名。倉庫的名字必須為此,否則無效。

3.2.發布項目

郵件Blazor項目,將其發布到本地文件夾中。由於沒有服務器交互,這里只需要將wwwroot目錄下的文件push到倉庫即可。

3.3.SPA解決方法

Github Pages本身支持多頁面程序的部署,為了托管Blazor這樣的SPA,需要通過404頁面的重定向來解決。步驟如下:

(1)創建404頁面

在wwwroot目錄下新建404.html,並在404頁面中寫入如下內容。注意,404頁面至少需要512個字節才能工作,所以可以直接將下面的所有內容都復制到404頁面中。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
      // Single Page Apps for GitHub Pages
      // https://github.com/rafrex/spa-github-pages
      // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
      // ----------------------------------------------------------------------
      // This script takes the current url and converts the path and query
      // string into just a query string, and then redirects the browser
      // to the new url with only a query string and hash fragment,
      // e.g. http://www.foo.tld/one/two?a=b&c=d#qwe, becomes
      // http://www.foo.tld/?p=/one/two&q=a=b~and~c=d#qwe
      // Note: this 404.html file must be at least 512 bytes for it to work
      // with Internet Explorer (it is currently > 512 bytes)

      // If you're creating a Project Pages site and NOT using a custom domain,
      // then set segmentCount to 1 (enterprise users may need to set it to > 1).
      // This way the code will only replace the route part of the path, and not
      // the real directory in which the app resides, for example:
      // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
      // https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe
      // Otherwise, leave segmentCount as 0.
      var segmentCount = 0;

      var l = window.location;
      l.replace(
        l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
        l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' +
        l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') +
        (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') +
        l.hash
      );

    </script>
  </head>
  <body>
  </body>
</html>

(2)更改index.html

在index頁面中加入重定向腳本,其腳本必須內嵌至index.html文件中,而且是在頁面的其他腳本執行之前執行。另外,如果index.html並不是在倉庫的根目錄下,還需要更改<base href="/" />為<base href="/folder/…/" />,以使得href+index.html能找到本頁面。最終樣子大概如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>title</title>
    <base href="/" />
    ...
</head>

<body>
    <app>Loading...</app>
     <!-- End Single Page Apps for GitHub Pages -->
    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>
    
    <!-- Start Single Page Apps for GitHub Pages -->
    <script type="text/javascript">
        // Single Page Apps for GitHub Pages
        // https://github.com/rafrex/spa-github-pages
        // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
        // ----------------------------------------------------------------------
        // This script checks to see if a redirect is present in the query string
        // and converts it back into the correct url and adds it to the
        // browser's history using window.history.replaceState(...),
        // which won't cause the browser to attempt to load the new url.
        // When the single page app is loaded further down in this file,
        // the correct url will be waiting in the browser's history for
        // the single page app to route accordingly.
        (function(l) {
            if (l.search) {
                var q = {};
                l.search.slice(1).split('&').forEach(function(v) {
                    var a = v.split('=');
                    q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&');
                });
                if (q.p !== undefined) {
                    window.history.replaceState(null, null,
                        l.pathname.slice(0, -1) + (q.p || '') +
                        (q.q ? ('?' + q.q) : '') +
                        l.hash
                    );
                }
            }
        }(window.location))
    </script>
   
    <!-- Temporary polyfill for IE support -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise,fetch"></script>    
    <script src="_framework/blazor.webassembly.js"></script>
    ...
</body>
</html>

3.4.添加Jekyll file

GitHub Pages使用的是Jekyll,凡是以“_”、“.”、“#”開頭或是以“~”結尾的文件、文件夾均不會本構建到網站中。而blazor中會用到_framework和_content中的資源,為了解決這個“bug”,需要在倉庫的根目錄下創建一個“.nojekyll”的空文件。

3.5.Failed to find a valid digest in the 'integrity' attribute for resource…

如果這樣就將倉庫push到github,很有可能會遇到如下問題:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://xxx/_framework/wasm/dotnet.3.2.0-preview2.20159.2.js' with computed SHA-256 integrity 'FJC7gQVpQ5ZmLsci9Oxg/MIH96sVbWXaxI5G3fM7Doc='. The resource has been blocked.

這個問題可以在github上找到解決方案:https://github.com/dotnet/aspnetcore/issues/19907。其中有兩個說法,都是需要配置.gitattributes,一個是添加autocrlf=false,另外一個是添加* binary。將這兩個配置添加到.gitattributes后,執行push,這樣才能通過userName.github.io正常的訪問到blazor應用程序。

示例:https://github.com/zxyao145/zxyao145.github.io/ByNotice,And歡迎大家start ByNotice 😊,一個完全使用blazor和css實現的通知組件。

本文參考:

https://github.com/rafrex/spa-github-pages

https://github.com/blazor-demo/blazor-demo.github.io


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM