dotnet / dotnet/aspnetcore

Static assets not working in ASP.NET Core MVC Views

Open
#59,003 3 comments 5 reactions 2 assignees Claimed by @javiercn View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [x] 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 `` 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:

```cs
... // 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;
itemsPropertyDictionary?.Add("__EndpointRouteBuilder", app);
controllerActionEndpointConventionBuilder.WithStaticAssets();
// End patch
```

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.