Last active
June 5, 2021 15:08
-
-
Save manoj-choudhari-git/62aac322593bdaa2461ce053826fb9ea to your computer and use it in GitHub Desktop.
.NET Core Web API - Configure Response Caching Middleware
This file contains 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
// 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