dotnet / dotnet/aspnetcore

Determine if request is for static asset

Open
#58,358 2 comments 1 reaction 0 assignees View on GitHub
area-blazor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

In our setup we have configured static file middleware to run very early in the pipeline; no point in running authentication checks for files read from disk. When we receive an authenticated request, we make a back-end call to ensure that the user is still enabled.

We have been looking into the new static web asset functionality in .NET 9. Since this requires things to run much later in the pipeline, authentication checks are made.

` If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAuthorization() must go between them.'`

We already run custom code during authentication, so we can check if the request is static asset request.

### Describe the solution you'd like

I'd like a public API we can use to check if the incoming request is for a static asset. This can then be used multiple places for how to handle things.
As a workaround, I've created this extensions method

```cs
public static bool IsStaticAsset(this HttpContext httpContext)
{
ArgumentNullException.ThrowIfNull(httpContext);
const string Key = "StaticAsset";

var endpoint = httpContext.GetEndpoint();
if (endpoint is null ||
httpContext.Items.ContainsKey(Key))
{
return true;
}

foreach (var metadata in endpoint.Metadata)
{
// this is part of the .NET 9 static web assets, this type is not public so we can only check on name
if (metadata.GetType().FullName?.Equals("Microsoft.AspNetCore.StaticAssets.BuildAssetMetadata", StringComparison.OrdinalIgnoreCase) == true)
{
httpContext.Items.Add(Key, true);
return true;
}
}

return false;
}
```

### Additional context

_No response_

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.