Files
mixtape/zero.Api/Filters/DisableBrowserCacheFilter.cs
T

33 lines
1011 B
C#
Raw Normal View History

2021-11-23 15:43:21 +01:00
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Net.Http.Headers;
2021-11-29 18:25:50 +01:00
namespace zero.Api.Controllers;
2021-11-23 15:43:21 +01:00
/// <summary>
/// Ensures that the request is not cached by the browser
/// </summary>
2021-12-12 21:05:08 +01:00
public class DisableBrowserCacheFilterAttribute : ActionFilterAttribute
2021-11-23 15:43:21 +01:00
{
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
var httpResponse = context.HttpContext.Response;
if (httpResponse.StatusCode != 200) return;
httpResponse.GetTypedHeaders().CacheControl =
new CacheControlHeaderValue()
{
NoCache = true,
MaxAge = TimeSpan.Zero,
MustRevalidate = true,
NoStore = true
};
httpResponse.Headers[HeaderNames.LastModified] = DateTime.Now.ToString("R"); // Format RFC1123
httpResponse.Headers[HeaderNames.Pragma] = "no-cache";
httpResponse.Headers[HeaderNames.Expires] = new DateTime(1990, 1, 1, 0, 0, 0).ToString("R");
}
}