Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VCST-2599: Add NoCacheForApiMiddleware to prevent API response caching #2877

Merged
merged 4 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading