Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active June 5, 2021 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/62aac322593bdaa2461ce053826fb9ea to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/62aac322593bdaa2461ce053826fb9ea to your computer and use it in GitHub Desktop.
.NET Core Web API - Configure Response Caching Middleware
// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Response Caching Middleware
services.AddResponseCaching(options =>
{
// Each response cannot be more than 1 KB
options.MaximumBodySize = 1024;
// Case Sensitive Paths
// Responses to be returned only if case sensitive paths match
options.UseCaseSensitivePaths = true;
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(
"v1", new OpenApiInfo { Title = "WebApiResponseCachingDemo", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(
c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiResponseCachingDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
// CORS Should be before Response Caching
app.UseCors();
// Response Caching Middleware
app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
// ValuesController.cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// ResponseCacheAttribute is to set caching headers
[HttpGet]
[ResponseCache(NoStore = false, Duration = 10, Location = ResponseCacheLocation.Any)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", DateTime.Now.ToString() };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment