Search code examples
javascript.netasp.net-corerazor-pages

Collocated Javascript files fail to load when ASPNETCORE_ENVIRONMENT set to Production


In a .NET 8 razor pages app, when I switch my ASPNETCORE_ENVIRONMENT environment variable to Production, my app works perfectly normally except that it does not load javascript files that aren't located directly in the wwwroot folder.

All my appsettings.json files are identical and do not change depending on ASPNETCORE_ENVIRONMENT.

For example, I have a razor page in the path \Areas\Admin\Pages\Dashboard\Index.cshtml, and an accompanying javascript file \Areas\Admin\Pages\Dashboard\Index.cshtml.js. This works great when ASPNETCORE_ENVIRONMENT is set to Development, but when set to Production, I get the following error in my browser: Failed to load resource: the server responded with a status of 404 (Not Found).

In addition to this, styles.css(which I assume is generated during the build process) also fails to load in the Production environment.

My script is included in the following way:


@section Scripts {
    <script src="~/Areas/Admin/Pages/Dashboard/Index.cshtml.js" asp-append-version="true"></script>
}

Additionally, after inspecting the publish folder, it seems the scripts are correctly placed in their file path: \bin\Release\net8.0\publish\wwwroot\Areas\Admin\Pages\Dashboard\Index.cshtml.js

Any ideas about what might be causing this are welcome.


Solution

  • After looking for any question somewhat similar to my issue, I found this post: AspCore 404 on production enviroment. This answer completely solved my issue:

    I added StaticWebAssetsLoader.UseStaticWebAssets(app.Environment, app.Configuration); to my program.cs file, and all the static files now load correctly in all environments.