Created
December 4, 2018 14:16
-
-
Save andyedinborough/70661a3c5c635cba15cf4777a6c1a612 to your computer and use it in GitHub Desktop.
ASP.NET Core Antiforgery with custom cache header value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Antiforgery.Internal; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Net.Http.Headers; | |
public class Antiforgery : DefaultAntiforgery | |
{ | |
public Antiforgery( | |
Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions> antiforgeryOptionsAccessor, | |
IAntiforgeryTokenGenerator tokenGenerator, | |
IAntiforgeryTokenSerializer tokenSerializer, | |
IAntiforgeryTokenStore tokenStore, | |
Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) | |
: base(antiforgeryOptionsAccessor, tokenGenerator, tokenSerializer, tokenStore, loggerFactory) | |
{ | |
} | |
protected override void SetDoNotCacheHeaders(HttpContext httpContext) | |
{ | |
CacheControlHeaderValue.TryParse(httpContext.Response.Headers[HeaderNames.CacheControl][0], out CacheControlHeaderValue cacheControlHeader); | |
if (cacheControlHeader == null) | |
{ | |
cacheControlHeader = new CacheControlHeaderValue(); | |
} | |
cacheControlHeader.NoCache = true; | |
cacheControlHeader.NoStore = true; | |
cacheControlHeader.MustRevalidate = true; | |
httpContext.Response.Headers[HeaderNames.CacheControl] = cacheControlHeader.ToString(); | |
httpContext.Response.Headers[HeaderNames.Pragma] = "no-cache"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddSingleton<Microsoft.AspNetCore.Antiforgery.IAntiforgery, Antiforgery>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment