Search code examples
blazorblazor-server-sideblazor-client-sideblazor-webassembly

Why is there a <base href="/" /> in Blazor's index.html or _Host.razor file?


In every Blazor project, there is a <base href="/"> inside of index.html or _Host.razor (depending on whether you're using Blazor WebAssembly or Blazor Server).

Now, I know what this tag does, simply any value put inside of its href attribute would be prepended to every relative path in the HTML document.

However, I don't understand why it's put there by default in every Blazor project. For example, if you're using Blazor WebAssembly, at the end of the index.html file there is this line:

<script src="_framework/blazor.webassembly.js"></script>

There is obviously no / in the beginning of this path because a <base href="/" /> is present in the document, but why couldn't they just simply add a leading / to this path so as to eliminate the need for the base tag altogether?! Why add the base tag?!

I've also tried removing the <base href="/" /> tag manually and instead added a leading / to all the paths, but then I quickly found out that doing so causes a problem: If you have a page that has a path like /counter/something (more than two levels), then the blazor.webassembly.js file, which after being loaded adds the other required JS files and assemblies to the HTML page dynamically, adds them without a leading slash and basically assumes that there is a <base href="/" />.

For example, blazor.webassembly.js loads a file with this path "_framework/blazor.boot.json". But in a scenario like the one I just explained, this would cause a 404 error as this is a relative path and there is no "/counter/_framework/blazor.boot.json".

So, this basically means that having a <base href="/" /> is effectively mandatory in every Blazor application! But why?!


Solution

  • From here

    The app base path is the app's root URL path. Consider the following ASP.NET Core app and Blazor sub-app:

    Without specifying additional configuration for CoolApp, the sub-app in this scenario has no knowledge of where it resides on the server. For example, the app can't construct correct relative URLs to its resources without knowing that it resides at the relative URL path /CoolApp/.