Skip to content

Commit cbb9a49

Browse files
authored
VCST-2599: Add NoCacheForApiMiddleware to prevent API response caching (#2877)
1 parent 558c367 commit cbb9a49

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Microsoft.AspNetCore.Http;
4+
5+
namespace VirtoCommerce.Platform.Web.Middleware;
6+
7+
public class NoCacheForApiMiddleware
8+
{
9+
private const string NoCache = "no-cache";
10+
private const string ExpiresMinusOne = "-1";
11+
12+
private readonly RequestDelegate _next;
13+
14+
public NoCacheForApiMiddleware(RequestDelegate next)
15+
{
16+
_next = next;
17+
}
18+
19+
public Task InvokeAsync(HttpContext context)
20+
{
21+
// Apply Cache-Control header for API responses
22+
if (context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
23+
{
24+
context.Response.Headers.CacheControl = NoCache;
25+
context.Response.Headers.Pragma = NoCache;
26+
context.Response.Headers.Expires = ExpiresMinusOne;
27+
}
28+
29+
// Proceed with the request pipeline
30+
return _next(context);
31+
}
32+
}

src/VirtoCommerce.Platform.Web/Startup.cs

+2
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<
597597

598598
app.UseSecurityHeaders();
599599

600+
app.UseMiddleware<NoCacheForApiMiddleware>();
601+
600602
//Return all errors as Json response
601603
app.UseMiddleware<ApiErrorWrappingMiddleware>();
602604

0 commit comments

Comments
 (0)