In a Blazor Application, how can I make the base URL different depending whether the application is executing on GitHub or my local machine?

Viewed 965

I have a blazor application which is being hosted on GitHub pages.

This is the index.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>Bitcoin Challenge Blazor App</title>
    <base href="/BitcoinChallengeBlazor/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
</head>

<body>
    <app>Loading...</app>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss"></a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>

</html>

On GitHub pages, the base needs to be <base href="/BitcoinChallengeBlazor/" />. However, when developing locally, the base needs to be <base href="/" />.

In theory, I could just change it and tell git that this change belongs to a different changeset. But it seems to me there should be a better way to do this which will include the correct value according to the environment, possibly using launchSettings.json or appsettings.json.

... but it's not obvious to me how I could make values from either/both of those files available in that exact context.

Any ideas?

2 Answers

Using PowerShell to modify the index.html file:

$PathToWebServer = "\\web05\wwwroot\client-apps\tenant-1\wwwroot\index.html"
$StringToFind ='<base href="/" />'
$StringToReplace ='<base href="/client-apps/tenant-1/" />'

(Get-Content -path $PathToWebServer -Raw) -replace $StringToFind,$StringToReplace | Set-Content -Path $PathToWebServer

I found a workaround.

Generate <base href="..." > tag on runtime:

  • Place <base href="/BitcoinChallengeBlazor/"> tag if any matches:
    • url pathname starts with /BitcoinChallengeBlazor/
    • url pathname is /BitcoinChallengeBlazor
  • Otherwise place <base href="/"> tag
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>APPNAME</title>
    <script>
        var baseTag = document.createElement("base");
        var appRoot = "/BitcoinChallengeBlazor/";
        var path = document.location.pathname;
        baseTag.href = (path.indexOf(appRoot) === 0 || path + "/" === appRoot) ? appRoot : "/";
        document.head.appendChild(baseTag);
    </script>
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link href="APPNAME.Client.styles.css" rel="stylesheet" />
</head>
Related