Skip to content

Static assets not working in ASP.NET Core MVC Views #59003

@jmaguilar

Description

@jmaguilar

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

The static assets feature does not seem to work with ASP.NET Core MVC views.

Despite configuring the application properly to use static assets, the rendered page code always references the original source file names without fingerprints and the import map is not generated.

Expected Behavior

After the MVC View is rendered, the generated page should:

  • Include the import map in the <head> section.
  • Use fingerprinted resource names for static file references.

Steps To Reproduce

Create a new ASP.NET Core MVC project and launch it.

Exceptions (if any)

No response

.NET Version

9.0.100

Anything else?

First, note that this is only happening in MVC Views. If we use Razor Pages with static assets, the rendered pages will be using the fingerprinted resources and the import map is generated fine.

Additionally, I've been digging a bit, and I think that the problem is that MapControllerRoute() -and other similar methods like MapDefaultControllerRoute()- are returning a builder that does not contain the item required by WithStaticAssets() to do its magic.

In fact, we can make it work using reflection:

... // Other Program.cs code

// Replace this:
// app.MapControllerRoute(
//    name: "default",
//    pattern: "{controller=Home}/{action=Index}/{id?}")
//    .WithStaticAssets();

// For this:
var controllerActionEndpointConventionBuilder = app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

var itemsProperty = controllerActionEndpointConventionBuilder
                                    .GetType()
                                    .GetProperty("Items", BindingFlags.NonPublic | BindingFlags.Instance);

var itemsPropertyDictionary = itemsProperty.GetValue(controllerActionEndpointConventionBuilder) as Dictionary<string, object>;
itemsPropertyDictionary?.Add("__EndpointRouteBuilder", app);
controllerActionEndpointConventionBuilder.WithStaticAssets();
// End patch

I hope it can help to pinpoint the root cause of the problem.

Metadata

Metadata

Labels

area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions