aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

MapStaticAssets, StaticWebAssetBasePath and multiple Blazor clients

Open ArcadeMode opened this issue 1 year ago • 4 comments

Is there an existing issue for this?

  • [x] I have searched the existing issues

Describe the bug

I have a Blazor Web application with 1 aspnetcore host and two blazor (webassembly) clients, all on .net9.0. I did not want to deal with hosting them on separate paths (through things like <base href=xx/> as it involved an existing application which would have been difficult to migrate, so they are exposed on separate domains.

To separate their assets I have been using "StaticWebAssetBasePath" in the csproj's to g et two folders in the wwwroot (say app-1 and app-2). So for the sake of discussion, i have app.com which gets (largely) served from wwwroot/app-1 and my.app.com which gets (largely) served from wwwroot/app-2. They are both able to use the same api which is accessible by route /api/xxx.

Some issues I had with this are that the server had to be modified slightly to point the applications to the correct paths for certain requests (mostly different PathBase)

  • the _content directory is published in the wwwroot instead of wwwroot/app-1, requests to assets here seem to work with the PathBase changes on the server.
  • resourcecollection.{fingerprint}.js and blazor.web.js do not exist on disk but generated by some middleware, it wont be served correctly unless the request pipeline has the correct PathBase set (app-1/app-2).
  • _framework/dotnet.js will not be found with these PathBase changes on the server. I have to manually prepend the PathBase again to find the file like /app-1/app-1/_framework/dotnet.js.

So at this point I hack in a little middleware that essentially checks for any path some.file if {pathbase}/some.file exists on disk. Note that this does mean we are already looking for app-1/_framework/dotnet.js so we add the "missing" segment.

Now here we are, up and running. A bit wacky that is has to be like this but sure. However, I noticed that fingerprinting is now suffering from the same weird double PathBase requirement issue:

  • Like with _framework/dotnet.js, I am already effectively serving /app-1/app-1/main.js. Even though the browser thinks its serving /main.js. To reiterate, I have to .UsePathBase in program.cs AND the middleware that adds the pathbase again, to the actual request path.
  • The fingerprinded asset paths (resolved in App.razor through the ComponentBase.Assets property) do not work either unless the path base is included in the path /app-1/main.js.

In the last point, I would be adding the pathbase THREE times. Amazingly, this would in turn break the resolution of _framework.dotnet.js and my middleware hack (which I am not keen on keeping) cannot work around this by checking for a file on disk, because only the StaticAssetsEndpointDataSource which knows which file the path may map to.

So I have gotten a bit stuck here.

Expected Behavior

  1. Static asset requests involving assets in a StaticAssetsBasePath directory need not add multiple PathBase's in the request uri to be resolved, wether they are fingerprinted or not.
  2. Fingerprinting url resolution considers the StaticAssetsBasePath

Steps To Reproduce

Sample blazor web repo + add an extra client.

Serve each client from a separate 'sub application' using MapWhen(ctx => domain == x, app => configureApp(app). and configure each app with a separate PathBase and UseEndpoints with MapStaticAssets and MapRazorComponents/MapRazorPages.

Then set the StaticAssetsBasePath in each blazor client's csproj file, matching the respective pathbases ofcourse.

Exceptions (if any)

No response

.NET Version

9.0.203

Anything else?

No response

ArcadeMode avatar Jun 04 '25 19:06 ArcadeMode

Hi, I am facing same scenario. Is there any ETA for this ?

michallabuzsybilla avatar Dec 03 '25 13:12 michallabuzsybilla

Im also facing the same issue

RayenSL avatar Jan 22 '26 14:01 RayenSL

Hi everyone, I've been working on a Blazor Web App (.NET 10) where I host multiple client applications (e.g., App1 and App2) within the same host project. I encountered a significant issue where WebAssembly framework assets—specifically _framework/dotnet.js—fail to resolve correctly because they are often requested from the root path by Web Workers, losing the context of the specific application prefix.

After experimenting with Blazor.start and JS-based fetch interceptors, I found that they are often bypassed by Web Workers or triggered too late. I've developed a robust workaround using a combination of Query Strings, Cookies, and Middleware Redirection.

The logic is simple:

  1. Identify the active application context in App.razor and append a query string to the blazor.web.js script tag.
  2. Capture this context in a middleware and store it in a cookie (which is accessible by Web Workers).
  3. If a framework request (like dotnet.js) hits the root but lacks the prefix, the middleware redirects it based on the cookie.
  4. It also handles Hot Reload pathing issues by stripping application prefixes from _content requests to prevent 404s during development.

Here is the implementation that solved the issue for me:

BlazorWebApp..csproj

  <ItemGroup>
    <ProjectReference Include="..\BlazorWebApp.Client.App1\BlazorWebApp.Client.App1.csproj" />
    <ProjectReference Include="..\BlazorWebApp.Client.App2\BlazorWebApp.Client.App2.csproj" />
  </ItemGroup>

BlazorWebApp.Client.App1.csproj <StaticWebAssetBasePath>App1</StaticWebAssetBasePath>

BlazorWebApp.Client.App2.csproj <StaticWebAssetBasePath>App2</StaticWebAssetBasePath>

App.razor We determine the client type and pass it as a query parameter to ensure the server knows the initial context.

@inject IHttpContextAccessor HttpContextAccessor 
@{
    var path = HttpContextAccessor.HttpContext?.Request.Path.Value ?? "";
    var isApp1 = path.StartsWith("/App1", StringComparison.OrdinalIgnoreCase);
    var isApp2 = path.StartsWith("/App2", StringComparison.OrdinalIgnoreCase);
    // Append context to the script source
    var jsSource = "_framework/blazor.web.js" + (isApp1 ? "?client=App1" : (isApp2 ? "?client=App2" : ""));
    InteractiveWebAssemblyRenderMode renderMode = new(prerender: false);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <ResourcePreloader />
    <link rel="stylesheet" href="@Assets["app.css"]" />
    <link rel="stylesheet" href="@Assets["BlazorWebApp.styles.css"]" />
    <ImportMap />
    <HeadOutlet @rendermode="renderMode" />
</head>
<body>
    <div id="app">
        @if (isApp1)
        {
            <BlazorWebApp.Client.App1.Routes @rendermode="renderMode" />
        }
        else if (isApp2)
        {
            <BlazorWebApp.Client.App2.Routes @rendermode="renderMode" />
        }
    </div>
    <div id="blazor-error-ui" data-nosnippet>
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">🗙</span>
    </div>
    <script src="@Assets[jsSource]"></script>
</body>
</html>

Program.cs The middleware manages the application state via cookies and performs the necessary redirects for framework files and Hot Reload assets.

app.Use(async (context, next) =>
{
    // Capture the client context from the script request
    if (context.Request.Query.TryGetValue("client", out var client))
    {
        context.Response.Cookies.Append("X-Client-App", client!, new CookieOptions
        {
            Path = "/",
            SameSite = SameSiteMode.Lax
        });
    }
    else
    {
        var path = context.Request.Path;
        // Redirect root framework requests to the specific application subfolder
        if (path.StartsWithSegments("/_framework/dotnet.js", StringComparison.OrdinalIgnoreCase))
        {
            if (context.Request.Cookies.TryGetValue("X-Client-App", out var app))
            {
                context.Response.Redirect($"/{app}{path}", permanent: false);
                return;
            }
        }
        // Handle Hot Reload assets which must resolve to the root _content folder
        else if (path.Value?.Contains("_content/Microsoft.DotNet.HotReload.WebAssembly.Browser") == true)
        {
            if (context.Request.Cookies.TryGetValue("X-Client-App", out var app) && 
                path.StartsWithSegments("/" + app + "/_content/Microsoft.DotNet.HotReload.WebAssembly.Browser", StringComparison.OrdinalIgnoreCase))
            {
                var newPath = path.Value.Replace("/" + app + "/_content/", "/_content/", StringComparison.OrdinalIgnoreCase);
                context.Response.Redirect(newPath, permanent: false);
                return;
            }
        }
    }
    await next();
});

app.MapRazorComponents<App>()
   .AddInteractiveWebAssemblyRenderMode()
   .AddAdditionalAssemblies(typeof(Client.App1._Imports).Assembly, typeof(Client.App2._Imports).Assembly);

 app.Run();

This approach ensures that even requests initiated by Web Workers (which ignore manual JS interceptions) are correctly routed by the server using the persisted cookie state. I hope this helps anyone facing similar issues with multi-tenant or multi-app Blazor WASM configurations.

I hope the issue will be permanently resolved. I will continue to follow up on this matter.

Best regards.

hyigit-adelcon avatar Jan 24 '26 22:01 hyigit-adelcon

I created a sample here - it has multiple clients libs, assets splitting, cache busting and public SSR vs 2 areas with 2 clients: https://github.com/rogihee/MultipleClientsBlazorWebApp Demo at https://multiple-clients-blazor.azurewebsites.net/ (for the time being).

rogihee avatar Oct 17 '26 08:10 rogihee