Merge pull request #5279 from aspnet/master

Update live with current master
pull/5342/head
Rick Anderson 2018-01-26 13:40:14 -10:00 committed by GitHub
commit 18ff1fdaa3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 494 additions and 140 deletions

View File

@ -212,7 +212,7 @@ The [CommandLine configuration provider](/aspnet/core/api/microsoft.extensions.c
# [Basic Configuration](#tab/basicconfiguration)
To activate command-line configuration, call the `AddCommandLine` extension method on an instance of [ConfigurationBuilder](/api/microsoft.extensions.configuration.configurationbuilder):
To activate command-line configuration, call the `AddCommandLine` extension method on an instance of [ConfigurationBuilder](/dotnet/api/microsoft.extensions.configuration.configurationbuilder):
[!code-csharp[Main](index/sample_snapshot//CommandLine/Program.cs?highlight=18,21)]

View File

@ -1,10 +1,11 @@
---
title: Response Caching Middleware in ASP.NET Core
author: guardrex
description: Learn how to configure and use Response Caching Middleware in ASP.NET Core apps.
description: Learn how to configure and use Response Caching Middleware in ASP.NET Core.
ms.author: riande
manager: wpickett
ms.date: 08/22/2017
ms.custom: mvc
ms.date: 01/26/2017
ms.topic: article
ms.prod: asp.net-core
uid: performance/caching/middleware
@ -13,44 +14,31 @@ uid: performance/caching/middleware
By [Luke Latham](https://github.com/guardrex) and [John Luo](https://github.com/JunTaoLuo)
[View or download sample code](https://github.com/aspnet/Docs/tree/master/aspnetcore/performance/caching/middleware/samples) ([how to download](xref:tutorials/index#how-to-download-a-sample))
[View or download sample code](https://github.com/aspnet/Docs/tree/master/aspnetcore/performance/caching/middleware/sample) ([how to download](xref:tutorials/index#how-to-download-a-sample))
This document provides details on how to configure the Response Caching Middleware in ASP.NET Core apps. The middleware determines when responses are cacheable, stores responses, and serves responses from cache. For an introduction to HTTP caching and the `ResponseCache` attribute, see [Response Caching](response.md).
This article explains how to configure Response Caching Middleware in an ASP.NET Core app. The middleware determines when responses are cacheable, stores responses, and serves responses from cache. For an introduction to HTTP caching and the `ResponseCache` attribute, see [Response Caching](xref:performance/caching/response).
## Package
To include the middleware in a project, add a reference to the [`Microsoft.AspNetCore.ResponseCaching`](https://www.nuget.org/packages/Microsoft.AspNetCore.ResponseCaching/) package or use the [`Microsoft.AspNetCore.All`](https://www.nuget.org/packages/Microsoft.AspNetCore.All/) package.
To include the middleware in a project, add a reference to the [`Microsoft.AspNetCore.ResponseCaching`](https://www.nuget.org/packages/Microsoft.AspNetCore.ResponseCaching/) package or use the [`Microsoft.AspNetCore.All`](https://www.nuget.org/packages/Microsoft.AspNetCore.All/) package (ASP.NET Core 2.0 or later when targeting .NET Core).
## Configuration
In `ConfigureServices`, add the middleware to the service collection.
# [ASP.NET Core 2.x](#tab/aspnetcore2x)
[!code-csharp[Main](middleware/samples/2.x/Program.cs?name=snippet1&highlight=4)]
# [ASP.NET Core 1.x](#tab/aspnetcore1x)
[!code-csharp[Main](middleware/samples/1.x/Startup.cs?name=snippet1&highlight=3)]
---
[!code-csharp[Main](middleware/sample/Startup.cs?name=snippet1&highlight=3)]
Configure the app to use the middleware with the `UseResponseCaching` extension method, which adds the middleware to the request processing pipeline. The sample app adds a [`Cache-Control`](https://tools.ietf.org/html/rfc7234#section-5.2) header to the response that caches cacheable responses for up to 10 seconds. The sample sends a [`Vary`](https://tools.ietf.org/html/rfc7231#section-7.1.4) header to configure the middleware to serve a cached response only if the [`Accept-Encoding`](https://tools.ietf.org/html/rfc7231#section-5.3.4) header of subsequent requests matches that of the original request.
# [ASP.NET Core 2.x](#tab/aspnetcore2x)
[!code-csharp[Main](middleware/sample/Startup.cs?name=snippet2&highlight=3,7-12)]
[!code-csharp[Main](middleware/samples/2.x/Program.cs?name=snippet1&highlight=8)]
# [ASP.NET Core 1.x](#tab/aspnetcore1x)
[!code-csharp[Main](middleware/samples/1.x/Startup.cs?name=snippet2&highlight=3)]
---
The Response Caching Middleware only caches 200 (OK) server responses. Any other responses, including [error pages](xref:fundamentals/error-handling), are ignored by the middleware.
Response Caching Middleware only caches server responses that result in a 200 (OK) status code. Any other responses, including [error pages](xref:fundamentals/error-handling), are ignored by the middleware.
> [!WARNING]
> Responses containing content for authenticated clients must be marked as not cacheable to prevent the middleware from storing and serving those responses. See [Conditions for caching](#conditions-for-caching) for details on how the middleware determines if a response is cacheable.
## Options
The middleware offers three options for controlling response caching.
| Option | Default Value |
@ -59,7 +47,10 @@ The middleware offers three options for controlling response caching.
| MaximumBodySize | The largest cacheable size for the response body in bytes.</p>The default value is `64 * 1024 * 1024` (64 MB). |
| SizeLimit | The size limit for the response cache middleware in bytes. The default value is `100 * 1024 * 1024` (100 MB). |
The following example configures the middleware to cache responses smaller than or equal to 1,024 bytes using case-sensitive paths, storing the responses to `/page1` and `/Page1` separately.
The following example configures the middleware to:
* Cache responses smaller than or equal to 1,024 bytes.
* Store the responses by case-sensitive paths (for example, `/page1` and `/Page1` are stored separately).
```csharp
services.AddResponseCaching(options =>
@ -70,9 +61,10 @@ services.AddResponseCaching(options =>
```
## VaryByQueryKeys
When using MVC, the `ResponseCache` attribute specifies the parameters necessary for setting appropriate headers for response caching. The only parameter of the `ResponseCache` attribute that strictly requires the middleware is `VaryByQueryKeys`, which doesn't correspond to an actual HTTP header. For more information, see [ResponseCache Attribute](response.md#responsecache-attribute).
When not using MVC, you can vary response caching with the `VaryByQueryKeys` feature. Use the `ResponseCachingFeature` directly from the `IFeatureCollection` of the `HttpContext`:
When using MVC/Web API controllers or Razor Pages page models, the `ResponseCache` attribute specifies the parameters necessary for setting the appropriate headers for response caching. The only parameter of the `ResponseCache` attribute that strictly requires the middleware is `VaryByQueryKeys`, which doesn't correspond to an actual HTTP header. For more information, see [ResponseCache Attribute](xref:performance/caching/response#responsecache-attribute).
When not using the `ResponseCache` attribute, response caching can be varied with the `VaryByQueryKeys` feature. Use the `ResponseCachingFeature` directly from the `IFeatureCollection` of the `HttpContext`:
```csharp
var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();
@ -83,15 +75,16 @@ if (responseCachingFeature != null)
```
## HTTP headers used by Response Caching Middleware
Response caching by the middleware is configured via HTTP headers. The relevant headers are listed below with notes on how they affect caching.
Response caching by the middleware is configured using HTTP headers.
| Header | Details |
| ------ | ------- |
| Authorization | The response isn't cached if the header exists. |
| Cache-Control | The middleware only considers caching responses marked with the `public` cache directive. You can control caching with the following parameters:<ul><li>max-age</li><li>max-stale&#8224;</li><li>min-fresh</li><li>must-revalidate</li><li>no-cache</li><li>no-store</li><li>only-if-cached</li><li>private</li><li>public</li><li>s-maxage</li><li>proxy-revalidate&#8225;</li></ul>&#8224;If no limit is specified to `max-stale`, the middleware takes no action.<br>&#8225;`proxy-revalidate` has the same effect as `must-revalidate`.<br><br>For more information, see [RFC 7231: Request Cache-Control Directives](https://tools.ietf.org/html/rfc7234#section-5.2.1). |
| Cache-Control | The middleware only considers caching responses marked with the `public` cache directive. Control caching with the following parameters:<ul><li>max-age</li><li>max-stale&#8224;</li><li>min-fresh</li><li>must-revalidate</li><li>no-cache</li><li>no-store</li><li>only-if-cached</li><li>private</li><li>public</li><li>s-maxage</li><li>proxy-revalidate&#8225;</li></ul>&#8224;If no limit is specified to `max-stale`, the middleware takes no action.<br>&#8225;`proxy-revalidate` has the same effect as `must-revalidate`.<br><br>For more information, see [RFC 7231: Request Cache-Control Directives](https://tools.ietf.org/html/rfc7234#section-5.2.1). |
| Pragma | A `Pragma: no-cache` header in the request produces the same effect as `Cache-Control: no-cache`. This header is overridden by the relevant directives in the `Cache-Control` header, if present. Considered for backward compatibility with HTTP/1.0. |
| Set-Cookie | The response isn't cached if the header exists. |
| Vary | The `Vary` header is used to vary the cached response by another header. For example, you can cache responses by encoding by including the `Vary: Accept-Encoding` header, which caches responses for requests with headers `Accept-Encoding: gzip` and `Accept-Encoding: text/plain` separately. A response with a header value of `*` is never stored. |
| Vary | The `Vary` header is used to vary the cached response by another header. For example, cache responses by encoding by including the `Vary: Accept-Encoding` header, which caches responses for requests with headers `Accept-Encoding: gzip` and `Accept-Encoding: text/plain` separately. A response with a header value of `*` is never stored. |
| Expires | A response deemed stale by this header isn't stored or retrieved unless overridden by other `Cache-Control` headers. |
| If-None-Match | The full response is served from cache if the value isn't `*` and the `ETag` of the response doesn't match any of the values provided. Otherwise, a 304 (Not Modified) response is served. |
| If-Modified-Since | If the `If-None-Match` header isn't present, a full response is served from cache if the cached response date is newer than the value provided. Otherwise, a 304 (Not Modified) response is served. |
@ -101,9 +94,9 @@ Response caching by the middleware is configured via HTTP headers. The relevant
## Caching respects request Cache-Control directives
The middleware respects the rules of the [HTTP 1.1 Caching specification](https://tools.ietf.org/html/rfc7234#section-5.2). The rules require a cache to honor a valid `Cache-Control` header sent by the client. Under the specification, a client can make requests with a `no-cache` header value and force a server to generate a new response for every request. Currently, there's no developer control over this caching behavior when using the middleware because the middleware adheres to the official caching specification.
The middleware respects the rules of the [HTTP 1.1 Caching specification](https://tools.ietf.org/html/rfc7234#section-5.2). The rules require a cache to honor a valid `Cache-Control` header sent by the client. Under the specification, a client can make requests with a `no-cache` header value and force the server to generate a new response for every request. Currently, there's no developer control over this caching behavior when using the middleware because the middleware adheres to the official caching specification.
[Future enhancements to the middleware](https://github.com/aspnet/ResponseCaching/issues/96) will permit configuring the middleware for caching scenarios where the request `Cache-Control` header should be ignored when deciding to serve a cached response. If you seek more control over caching behavior, explore other caching features of ASP.NET Core. See the following topics:
For more control over caching behavior, explore other caching features of ASP.NET Core. See the following topics:
* [In-memory caching](xref:performance/caching/memory)
* [Working with a distributed cache](xref:performance/caching/distributed)
@ -111,27 +104,28 @@ The middleware respects the rules of the [HTTP 1.1 Caching specification](https:
* [Distributed Cache Tag Helper](xref:mvc/views/tag-helpers/builtin-th/distributed-cache-tag-helper)
## Troubleshooting
If caching behavior isn't as you expect, confirm that responses are cacheable and capable of being served from the cache by examining the request's incoming headers and the response's outgoing headers. Enabling [logging](xref:fundamentals/logging/index) can help when debugging. The middleware logs caching behavior and when a response is retrieved from cache.
When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. For example, a browser may set the `Cache-Control` header to `no-cache` when you refresh the page. The following tools can explicitly set request headers, and are preferred for testing caching:
If caching behavior isn't as expected, confirm that responses are cacheable and capable of being served from the cache. Examine the request's incoming headers and the response's outgoing headers. Enable [logging](xref:fundamentals/logging/index) to help with debugging.
* [Fiddler](http://www.telerik.com/fiddler)
* [Firebug](http://getfirebug.com/)
When testing and troubleshooting caching behavior, a browser may set request headers that affect caching in undesirable ways. For example, a browser may set the `Cache-Control` header to `no-cache` or `max-age=0` when refreshing a page. The following tools can explicitly set request headers and are preferred for testing caching:
* [Fiddler](https://www.telerik.com/fiddler)
* [Postman](https://www.getpostman.com/)
### Conditions for caching
* The request must result in a 200 (OK) response from the server.
* The request must result in a server response with a 200 (OK) status code.
* The request method must be GET or HEAD.
* Terminal middleware, such as Static File Middleware, must not process the response prior to the Response Caching Middleware.
* Terminal middleware, such as [Static File Middleware](xref:fundamentals/static-files), must not process the response prior to the Response Caching Middleware.
* The `Authorization` header must not be present.
* `Cache-Control` header parameters must be valid, and the response must be marked `public` and not marked `private`.
* The `Pragma: no-cache` header/value must not be present if the `Cache-Control` header isn't present, as the `Cache-Control` header overrides the `Pragma` header when present.
* The `Pragma: no-cache` header must not be present if the `Cache-Control` header isn't present, as the `Cache-Control` header overrides the `Pragma` header when present.
* The `Set-Cookie` header must not be present.
* `Vary` header parameters must be valid and not equal to `*`.
* The `Content-Length` header value (if set) must match the size of the response body.
* The [IHttpSendFileFeature](/aspnet/core/api/microsoft.aspnetcore.http.features.ihttpsendfilefeature) isn't used.
* The response must not be stale as specified by the `Expires` header and the `max-age` and `s-maxage` cache directives.
* Response buffering is successful, and the size of the response is smaller than the configured or default `SizeLimit`.
* Response buffering must be successful, and the size of the response must be smaller than the configured or default `SizeLimit`.
* The response must be cacheable according to the [RFC 7234](https://tools.ietf.org/html/rfc7234) specifications. For example, the `no-store` directive must not exist in request or response header fields. See *Section 3: Storing Responses in Caches* of [RFC 7234](https://tools.ietf.org/html/rfc7234) for details.
> [!NOTE]

View File

@ -0,0 +1,3 @@
{
"directory": "wwwroot/lib"
}

View File

@ -0,0 +1,217 @@
_build/
_site/
Properties/
# Use git add -f to force override .sln when required. Not needed in most cases.
# git add -f myProj.sln
*.sln
Project_Readme.html
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.vscode/
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studo 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
*.[Cc]ache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
project.lock.json
**/sample/**/wwwroot/lib/
**/samples/**/wwwroot/lib/
__pycache__/
#Mac OSX
.DS_Store
# Windows thumbnail cache files
Thumbs.db

View File

@ -0,0 +1,23 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Response Caching Middleware";
}
<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Instructions</h3>
</div>
<div class="panel-body">
<p>Current server time at time of page generation: @System.DateTime.Now</p>
<p>The app responds with its Index page, including a <code>Cache-Control</code> header to configure caching behavior. The app also sets the <code>Vary</code> header to configure the cache to serve the response only if the <code>Accept-Encoding</code> header of subsequent requests matches that from the original request.</p>
<p>When running the sample, the Index page is served from cache when stored and cached for up to 10 seconds.</p>
<p>Don't use a browser to test caching behavior. Browsers often add a <code>Cache-Control</code> header (for example, <code>max-age=0</code>) on reload that prevent the middleware from serving a cached page. To test caching behavior, use a tool like <a href="http://www.telerik.com/fiddler">Fiddler</a>, <a href="http://getfirebug.com/">Firebug</a>, or <a href="https://www.getpostman.com/">Postman</a>.</p>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ResponseCachingMiddleware.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -0,0 +1,70 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewData["Title"] - Response Caching Middleware</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="~/css/site.css">
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u">
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true">
</environment>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-page="/Index" class="navbar-brand">Response Caching Middleware</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-page="/Index">Home</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
@RenderBody()
<hr>
<footer>
<p>&copy;@System.DateTime.Now.Year - Response Caching Middleware</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
@RenderSection("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,3 @@
@using ResponseCachingMiddleware
@namespace ResponseCachingMiddleware.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,18 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace ResponseCachingMiddleware
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}

View File

@ -0,0 +1,7 @@
# ASP.NET Core Response Caching Sample
This sample illustrates the usage of ASP.NET Core [Response Caching Middleware](https://docs.microsoft.com/aspnet/core/performance/caching/middleware).
The app responds with its Index page, including a `Cache-Control` header to configure caching behavior. The app also sets the `Vary` header to configure the cache to serve the response only if the `Accept-Encoding` header of subsequent requests matches that from the original request.
When running the sample, the Index page is served from cache when stored and cached for up to 10 seconds.

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.0</TargetFrameworks>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>

View File

@ -1,13 +1,11 @@
using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace ResponseCachingSample
namespace ResponseCachingMiddleware
{
public class Startup
{
@ -15,15 +13,16 @@ namespace ResponseCachingSample
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
services.AddMvc();
}
#endregion
#region snippet2
public void Configure(IApplicationBuilder app)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCaching();
app.Run(async (context) =>
app.Use(async (context, next) =>
{
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
@ -32,25 +31,17 @@ namespace ResponseCachingSample
};
context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
await context.Response.WriteAsync($"Hello World! {DateTime.UtcNow}");
await next();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
}
#endregion
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.ConfigureLogging(factory =>
{
factory.AddConsole(LogLevel.Debug);
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug"
}
}
}

View File

@ -0,0 +1,10 @@
{
"name": "asp.net",
"private": true,
"dependencies": {
"bootstrap": "3.3.7",
"jquery": "2.2.0",
"jquery-validation": "1.14.0",
"jquery-validation-unobtrusive": "3.2.6"
}
}

View File

@ -0,0 +1,24 @@
// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
{
"outputFileName": "wwwroot/css/site.min.css",
// An array of relative input file paths. Globbing patterns supported
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
// Optionally specify minification options
"minify": {
"enabled": true,
"renameLocals": true
},
// Optionally generate .map file
"sourceMap": false
}
]

View File

@ -0,0 +1,25 @@
body {
padding-top: 50px;
padding-bottom: 20px;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 20px;
}
h3 {
font-size:16px
}
.body-content {
padding-left: 15px;
padding-right: 15px;
}
.panel-body {
font-size: 16px;
}

View File

@ -0,0 +1 @@
body{padding-top:50px;padding-bottom:20px}h1{font-size:24px}h2{font-size:20px}h3{font-size:16px}.body-content{padding-left:15px;padding-right:15px}.panel-body{font-size:16px}

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -0,0 +1 @@
// Write your Javascript code.

View File

@ -1,7 +0,0 @@
# ASP.NET Core Response Caching Sample (ASP.NET Core 1.x)
This sample illustrates the usage of ASP.NET Core [Response Caching Middleware](xref:performance/caching/middleware) with ASP.NET Core 1.x. For the ASP.NET Core 2.x sample, see [ASP.NET Core Response Caching Sample (ASP.NET Core 2.x)](https://github.com/aspnet/Docs/tree/master/aspnetcore/performance/caching/middleware/samples/2.x).
The application sends a `Hello World!` message and the current time along with a `Cache-Control` header to configure caching behavior. The application also sends a `Vary` header to configure the cache to serve the response only if the `Accept-Encoding` header of subsequent requests matches that from the original request.
When running the sample, a response is served from cache when possible and stored for up to 10 seconds.

View File

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFrameworks>net451;netcoreapp1.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.ResponseCaching" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
</ItemGroup>
</Project>

View File

@ -1,46 +0,0 @@
using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.ResponseCaching;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
namespace ResponseCachingSample
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
#region snippet1
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddResponseCaching();
})
.Configure(app =>
{
app.UseResponseCaching();
app.Run(async (context) =>
{
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(10)
};
context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
await context.Response.WriteAsync($"Hello World! {DateTime.UtcNow}");
});
})
.Build();
#endregion
}
}

View File

@ -1,7 +0,0 @@
# ASP.NET Core Response Caching Sample (ASP.NET Core 2.x)
This sample illustrates the usage of ASP.NET Core [Response Caching Middleware](xref:performance/caching/middleware) with ASP.NET Core 2.x. For the ASP.NET Core 1.x sample, see [ASP.NET Core Response Caching Sample (ASP.NET Core 1.x)](https://github.com/aspnet/Docs/tree/master/aspnetcore/performance/caching/middleware/samples/1.x).
The application sends a `Hello World!` message and the current time along with a `Cache-Control` header to configure caching behavior. The application also sends a `Vary` header to configure the cache to serve the response only if the `Accept-Encoding` header of subsequent requests matches that from the original request.
When running the sample, a response is served from cache when possible and stored for up to 10 seconds.