aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Determine if request is for static asset

Open dnv-kimbell opened this issue 1 year ago • 2 comments

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

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

dnv-kimbell avatar Oct 11 '24 06:10 dnv-kimbell

FYI @javiercn

amcasey avatar Oct 14 '24 22:10 amcasey

@dnv-kimbell thanks for contacting us.

We are taking note, I don't think we can add something for 9.0 at this point, but it's a legit request that we can consider for 10. Microsoft.AspNetCore.StaticAssets.BuildAssetMetadata I don't think this will work in production to detect the asset but you can add your own metadata to the assets to tag them by using app.MapStaticAssets().Add(new MyMetadata())

javiercn avatar Oct 15 '24 09:10 javiercn