Blazor webassembly base path issues.

If you’re uploading your blazor wasm project on a subdirectory on your host, you have likely hit a problem where you had to edit the <base href> in wwwroot/index.html to adjust.  But after you do this, launching the project on your local machine turns up with a path problem.
I had to edit the base href parameter each time to test locally, but there’s a sweet fix for this thanks to this post

Simply replace <base href> in index.html with the below:

<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>

Screenshot taken in case link goes bad:

 

Leave a Reply

Your email address will not be published. Required fields are marked *