Skip to content

Commit

Permalink
VCST-2599: Add NoCacheForApiMiddleware to prevent API response caching (
Browse files Browse the repository at this point in the history
  • Loading branch information
OlegoO authored Jan 31, 2025
1 parent 558c367 commit cbb9a49
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}
}
2 changes: 2 additions & 0 deletions src/VirtoCommerce.Platform.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<

app.UseSecurityHeaders();

app.UseMiddleware<NoCacheForApiMiddleware>();

//Return all errors as Json response
app.UseMiddleware<ApiErrorWrappingMiddleware>();

Expand Down

0 comments on commit cbb9a49

Please sign in to comment.