From cbb9a4920b2f4a89828b9a1010061e8cc2d7be8c Mon Sep 17 00:00:00 2001 From: Oleg Zhuk Date: Fri, 31 Jan 2025 19:55:04 +0200 Subject: [PATCH] VCST-2599: Add NoCacheForApiMiddleware to prevent API response caching (#2877) --- .../Middleware/NoCacheForApiMiddleware.cs | 32 +++++++++++++++++++ src/VirtoCommerce.Platform.Web/Startup.cs | 2 ++ 2 files changed, 34 insertions(+) create mode 100644 src/VirtoCommerce.Platform.Web/Middleware/NoCacheForApiMiddleware.cs diff --git a/src/VirtoCommerce.Platform.Web/Middleware/NoCacheForApiMiddleware.cs b/src/VirtoCommerce.Platform.Web/Middleware/NoCacheForApiMiddleware.cs new file mode 100644 index 00000000000..68411b3677b --- /dev/null +++ b/src/VirtoCommerce.Platform.Web/Middleware/NoCacheForApiMiddleware.cs @@ -0,0 +1,32 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace VirtoCommerce.Platform.Web.Middleware; + +public class NoCacheForApiMiddleware +{ + private const string NoCache = "no-cache"; + private const string ExpiresMinusOne = "-1"; + + private readonly RequestDelegate _next; + + public NoCacheForApiMiddleware(RequestDelegate next) + { + _next = next; + } + + public Task InvokeAsync(HttpContext context) + { + // Apply Cache-Control header for API responses + if (context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)) + { + context.Response.Headers.CacheControl = NoCache; + context.Response.Headers.Pragma = NoCache; + context.Response.Headers.Expires = ExpiresMinusOne; + } + + // Proceed with the request pipeline + return _next(context); + } +} diff --git a/src/VirtoCommerce.Platform.Web/Startup.cs b/src/VirtoCommerce.Platform.Web/Startup.cs index 13c435649cc..49c27060299 100644 --- a/src/VirtoCommerce.Platform.Web/Startup.cs +++ b/src/VirtoCommerce.Platform.Web/Startup.cs @@ -597,6 +597,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< app.UseSecurityHeaders(); + app.UseMiddleware(); + //Return all errors as Json response app.UseMiddleware();