diff --git a/AspNetCore.slnx b/AspNetCore.slnx
index 1b679cf56de4..ad26b409909a 100644
--- a/AspNetCore.slnx
+++ b/AspNetCore.slnx
@@ -1299,6 +1299,7 @@
+
diff --git a/src/StaticAssets/perf/Microbenchmarks/AssemblyInfo.cs b/src/StaticAssets/perf/Microbenchmarks/AssemblyInfo.cs
new file mode 100644
index 000000000000..09f49228e9e6
--- /dev/null
+++ b/src/StaticAssets/perf/Microbenchmarks/AssemblyInfo.cs
@@ -0,0 +1,4 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+[assembly: BenchmarkDotNet.Attributes.AspNetCoreBenchmark]
diff --git a/src/StaticAssets/perf/Microbenchmarks/Microsoft.AspNetCore.StaticAssets.Microbenchmarks.csproj b/src/StaticAssets/perf/Microbenchmarks/Microsoft.AspNetCore.StaticAssets.Microbenchmarks.csproj
new file mode 100644
index 000000000000..7a857d775477
--- /dev/null
+++ b/src/StaticAssets/perf/Microbenchmarks/Microsoft.AspNetCore.StaticAssets.Microbenchmarks.csproj
@@ -0,0 +1,33 @@
+
+
+
+ $(DefaultNetCoreTargetFramework)
+ Exe
+ true
+ Microsoft.AspNetCore.StaticAssets
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/StaticAssets/perf/Microbenchmarks/StaticAssetsInvokerBenchmark.cs b/src/StaticAssets/perf/Microbenchmarks/StaticAssetsInvokerBenchmark.cs
new file mode 100644
index 000000000000..2c8f49d549ec
--- /dev/null
+++ b/src/StaticAssets/perf/Microbenchmarks/StaticAssetsInvokerBenchmark.cs
@@ -0,0 +1,135 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Globalization;
+using System.Text.Json;
+using BenchmarkDotNet.Attributes;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.FileProviders;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Microsoft.AspNetCore.StaticAssets;
+
+// Invokes the real endpoint produced by MapStaticAssets for a publish (non-build) manifest,
+// so no development-time runtime handler is involved.
+public class StaticAssetsInvokerBenchmark
+{
+ private const string ETag = "\"Fa0yOlTdLpA5u5+vzI2jL3sZcGbSqTqxWDWdRxRxNTI=\"";
+
+ private string _root;
+ private ServiceProvider _services;
+ private RequestDelegate _requestDelegate;
+
+ [GlobalSetup]
+ public void Setup()
+ {
+ _root = Path.Combine(Path.GetTempPath(), "StaticAssetsInvokerBenchmark", Guid.NewGuid().ToString("N"));
+ var webRoot = Path.Combine(_root, "wwwroot");
+ Directory.CreateDirectory(webRoot);
+ File.WriteAllText(Path.Combine(webRoot, "site.css"), new string('a', 1024));
+
+ var manifestPath = Path.Combine(_root, "app.staticwebassets.endpoints.json");
+ File.WriteAllText(manifestPath, JsonSerializer.Serialize(new
+ {
+ Version = 1,
+ ManifestType = "Publish",
+ Endpoints = new[]
+ {
+ new StaticAssetDescriptor
+ {
+ Route = "site.css",
+ AssetPath = "site.css",
+ Selectors = [],
+ Properties = [],
+ ResponseHeaders =
+ [
+ new("Accept-Ranges", "bytes"),
+ new("Cache-Control", "max-age=31536000, immutable"),
+ new("Content-Length", "1024"),
+ new("Content-Type", "text/css"),
+ new("ETag", ETag),
+ new("Last-Modified", new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture)),
+ ],
+ },
+ },
+ }));
+
+ var services = new ServiceCollection();
+ services.AddSingleton(new ConfigurationBuilder().Build());
+ services.AddSingleton(NullLoggerFactory.Instance);
+ services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
+ services.AddSingleton(new BenchmarkWebHostEnvironment(_root, webRoot));
+ services.AddRouting();
+ _services = services.BuildServiceProvider();
+
+ var endpoints = new BenchmarkEndpointRouteBuilder(_services);
+ endpoints.MapStaticAssets(manifestPath);
+
+ var endpoint = endpoints.DataSources.SelectMany(d => d.Endpoints).OfType().Single();
+ _requestDelegate = endpoint.RequestDelegate;
+
+ if (Head200().GetAwaiter().GetResult() != StatusCodes.Status200OK ||
+ GetIfNoneMatch304().GetAwaiter().GetResult() != StatusCodes.Status304NotModified)
+ {
+ throw new InvalidOperationException("The benchmark requests did not produce the expected status codes.");
+ }
+ }
+
+ [GlobalCleanup]
+ public void Cleanup()
+ {
+ _services.Dispose();
+ Directory.Delete(_root, recursive: true);
+ }
+
+ [Benchmark]
+ public async Task Head200()
+ {
+ var context = CreateContext(HttpMethods.Head);
+ await _requestDelegate(context);
+ return context.Response.StatusCode;
+ }
+
+ [Benchmark]
+ public async Task GetIfNoneMatch304()
+ {
+ var context = CreateContext(HttpMethods.Get);
+ context.Request.Headers.IfNoneMatch = ETag;
+ await _requestDelegate(context);
+ return context.Response.StatusCode;
+ }
+
+ private DefaultHttpContext CreateContext(string method)
+ {
+ var context = new DefaultHttpContext { RequestServices = _services };
+ context.Request.Method = method;
+ context.Request.Path = "/site.css";
+ context.Response.Body = Stream.Null;
+ return context;
+ }
+
+ private sealed class BenchmarkEndpointRouteBuilder(IServiceProvider serviceProvider) : IEndpointRouteBuilder
+ {
+ public IServiceProvider ServiceProvider { get; } = serviceProvider;
+
+ public ICollection DataSources { get; } = new List();
+
+ public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider);
+ }
+
+ private sealed class BenchmarkWebHostEnvironment(string contentRoot, string webRoot) : IWebHostEnvironment
+ {
+ public string ApplicationName { get; set; } = "app";
+ public string EnvironmentName { get; set; } = "Production";
+ public string ContentRootPath { get; set; } = contentRoot;
+ public IFileProvider ContentRootFileProvider { get; set; } = new PhysicalFileProvider(contentRoot);
+ public string WebRootPath { get; set; } = webRoot;
+ public IFileProvider WebRootFileProvider { get; set; } = new PhysicalFileProvider(webRoot);
+ }
+}
diff --git a/src/StaticAssets/src/StaticAssetsInvoker.cs b/src/StaticAssets/src/StaticAssetsInvoker.cs
index c7555c901b93..047393c8d797 100644
--- a/src/StaticAssets/src/StaticAssetsInvoker.cs
+++ b/src/StaticAssets/src/StaticAssetsInvoker.cs
@@ -27,6 +27,10 @@ internal class StaticAssetsInvoker
private readonly DateTimeOffset _lastModified;
private readonly List _remainingHeaders;
+ // The ETag and Last-Modified values are fixed for a given asset, so format them once.
+ private readonly string _etagHeaderValue;
+ private readonly string _lastModifiedHeaderValue;
+
private IFileInfo? _fileInfo;
public StaticAssetsInvoker(StaticAssetDescriptor resource, IFileProvider fileProvider, ILogger logger)
@@ -75,6 +79,9 @@ public StaticAssetsInvoker(StaticAssetDescriptor resource, IFileProvider filePro
{
throw new InvalidOperationException("The ETag header is required.");
}
+
+ _etagHeaderValue = _etag.ToString();
+ _lastModifiedHeaderValue = HeaderUtilities.FormatDate(_lastModified);
}
public string Route => _resource.Route;
@@ -97,12 +104,12 @@ private Task ApplyResponseHeadersAsync(StaticAssetInvocationContext context, int
context.Response.ContentType = _contentType;
}
- var responseHeaders = context.ResponseHeaders;
- responseHeaders.LastModified = _lastModified;
- responseHeaders.ETag = _etag;
- responseHeaders.Headers.AcceptRanges = "bytes";
+ var responseHeaders = context.Response.Headers;
+ responseHeaders.LastModified = _lastModifiedHeaderValue;
+ responseHeaders.ETag = _etagHeaderValue;
+ responseHeaders.AcceptRanges = "bytes";
- foreach (var header in _remainingHeaders ?? [])
+ foreach (var header in _remainingHeaders)
{
responseHeaders.Append(header.Name, header.Value);
}
@@ -129,6 +136,7 @@ public async Task Invoke(HttpContext context)
var requestContext = new StaticAssetInvocationContext(
context,
_etag,
+ _etagHeaderValue,
_lastModified,
_length,
_logger);
@@ -254,6 +262,7 @@ private readonly struct StaticAssetInvocationContext
private readonly HttpContext _context = null!;
private readonly HttpRequest _request = null!;
private readonly EntityTagHeaderValue _etag;
+ private readonly string _etagHeaderValue;
private readonly DateTimeOffset _lastModified;
private readonly long _length;
private readonly ILogger _logger;
@@ -262,16 +271,17 @@ private readonly struct StaticAssetInvocationContext
public StaticAssetInvocationContext(
HttpContext context,
EntityTagHeaderValue entityTag,
+ string etagHeaderValue,
DateTimeOffset lastModified,
long length,
ILogger logger)
{
_context = context;
_request = context.Request;
- ResponseHeaders = context.Response.GetTypedHeaders();
_requestHeaders = _request.GetTypedHeaders();
Response = context.Response;
_etag = entityTag;
+ _etagHeaderValue = etagHeaderValue;
_lastModified = lastModified;
_length = length;
_logger = logger;
@@ -279,7 +289,8 @@ public StaticAssetInvocationContext(
public CancellationToken CancellationToken => _context.RequestAborted;
- public ResponseHeaders ResponseHeaders { get; }
+ // Only needed when sending Content-Range, so avoid allocating it for every request.
+ public ResponseHeaders ResponseHeaders => Response.GetTypedHeaders();
public HttpResponse Response { get; }
@@ -317,6 +328,14 @@ public StaticAssetInvocationContext(
// 14.26 If-None-Match
var ifNoneMatchResult = PreconditionState.Unspecified;
+
+ // Fast path for the common revalidation request that echoes back the exact ETag we sent.
+ var rawIfNoneMatch = _request.Headers.IfNoneMatch;
+ if (rawIfNoneMatch.Count == 1 && string.Equals(rawIfNoneMatch[0], _etagHeaderValue, StringComparison.Ordinal))
+ {
+ return (ifMatchResult, PreconditionState.NotModified);
+ }
+
var ifNoneMatch = requestHeaders.IfNoneMatch;
if (ifNoneMatch?.Count > 0)
{
diff --git a/src/StaticAssets/test/StaticAssetsIntegrationTests.cs b/src/StaticAssets/test/StaticAssetsIntegrationTests.cs
index b7d8375f9535..3780048554c8 100644
--- a/src/StaticAssets/test/StaticAssetsIntegrationTests.cs
+++ b/src/StaticAssets/test/StaticAssetsIntegrationTests.cs
@@ -1139,6 +1139,81 @@ public async Task RangeGivesMatchingRange()
Assert.Equal(5, res2.Content.Headers.ContentLength);
}
+ [Fact]
+ public async Task ResponseHeadersAreConsistentAcrossStatusCodes()
+ {
+ var client = await CreateClient();
+ var expectedETag = $"\"{GetEtag("Hello, World!")}\"";
+ const string expectedLastModified = "Fri, 03 Mar 2023 00:00:00 GMT";
+
+ var get = await client.GetAsync("http://localhost/sample.txt");
+ AssertHeaders(get, HttpStatusCode.OK);
+
+ var head = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "http://localhost/sample.txt"));
+ AssertHeaders(head, HttpStatusCode.OK);
+
+ var notModifiedRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
+ notModifiedRequest.Headers.TryAddWithoutValidation("If-None-Match", expectedETag);
+ var notModified = await client.SendAsync(notModifiedRequest);
+ AssertHeaders(notModified, HttpStatusCode.NotModified);
+
+ var rangeRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
+ rangeRequest.Headers.Range = new RangeHeaderValue(0, 4);
+ var range = await client.SendAsync(rangeRequest);
+ AssertHeaders(range, HttpStatusCode.PartialContent);
+ Assert.Equal("bytes 0-4/13", Assert.Single(range.Content.Headers.GetValues("Content-Range")));
+
+ var unsatisfiableRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
+ unsatisfiableRequest.Headers.Range = new RangeHeaderValue(100, 200);
+ var unsatisfiable = await client.SendAsync(unsatisfiableRequest);
+ Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, unsatisfiable.StatusCode);
+ Assert.Equal("bytes */13", Assert.Single(unsatisfiable.Content.Headers.GetValues("Content-Range")));
+ Assert.False(unsatisfiable.Headers.Contains("ETag"));
+ Assert.False(unsatisfiable.Content.Headers.Contains("Last-Modified"));
+
+ void AssertHeaders(HttpResponseMessage response, HttpStatusCode statusCode)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal(expectedETag, Assert.Single(response.Headers.GetValues("ETag")));
+ Assert.Equal(expectedLastModified, Assert.Single(response.Content.Headers.GetValues("Last-Modified")));
+ Assert.Contains("bytes", response.Headers.AcceptRanges);
+ }
+ }
+
+ [Theory]
+ [InlineData("{0}", HttpStatusCode.NotModified)]
+ [InlineData("W/{0}", HttpStatusCode.NotModified)]
+ [InlineData(" {0} ", HttpStatusCode.NotModified)]
+ [InlineData("\"other\", {0}", HttpStatusCode.NotModified)]
+ [InlineData("\"other\"", HttpStatusCode.OK)]
+ [InlineData("W/\"other\"", HttpStatusCode.OK)]
+ public async Task IfNoneMatchVariantsAreEvaluated(string ifNoneMatchFormat, HttpStatusCode expectedStatusCode)
+ {
+ var client = await CreateClient();
+ var etag = $"\"{GetEtag("Hello, World!")}\"";
+
+ var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
+ request.Headers.TryAddWithoutValidation("If-None-Match", string.Format(CultureInfo.InvariantCulture, ifNoneMatchFormat, etag));
+ var response = await client.SendAsync(request);
+
+ Assert.Equal(expectedStatusCode, response.StatusCode);
+ Assert.Equal(etag, Assert.Single(response.Headers.GetValues("ETag")));
+ }
+
+ [Fact]
+ public async Task IfMatchFailureTakesPrecedenceOverMatchingIfNoneMatch()
+ {
+ var client = await CreateClient();
+ var etag = $"\"{GetEtag("Hello, World!")}\"";
+
+ var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/sample.txt");
+ request.Headers.TryAddWithoutValidation("If-None-Match", etag);
+ request.Headers.TryAddWithoutValidation("If-Match", "\"other\"");
+ var response = await client.SendAsync(request);
+
+ Assert.Equal(HttpStatusCode.PreconditionFailed, response.StatusCode);
+ }
+
public static IEnumerable