ASP.NET Core MVC의 캐시 태그 도우미Cache Tag Helper in ASP.NET Core MVC
작성자: Peter Kellner 및 Luke LathamBy Peter Kellner and Luke Latham
캐시 태그 도우미는 콘텐츠를 내부 ASP.NET Core 캐시 공급자에 캐시하여 ASP.NET Core 앱 성능을 개선하는 기능을 제공합니다.The Cache Tag Helper provides the ability to improve the performance of your ASP.NET Core app by caching its content to the internal ASP.NET Core cache provider.
태그 도우미에 대한 개요는 ASP.NET Core의 태그 도우미를 참조하세요.For an overview of Tag Helpers, see ASP.NET Core의 태그 도우미.
다음 Razor 태그는 현재 날짜를 캐시합니다.The following Razor markup caches the current date:
<cache>@DateTime.Now</cache>
태그 도우미를 포함하는 페이지에 대한 첫 번째 요청은 현재 날짜를 표시합니다.The first request to the page that contains the Tag Helper displays the current date. 추가 요청은 캐시가 만료될 때까지(기본값 20분) 또는 캐시에서 캐시된 날짜가 제거될 때까지 캐시된 값을 표시합니다.Additional requests show the cached value until the cache expires (default 20 minutes) or until the cached date is evicted from the cache.
캐시 태그 도우미 특성Cache Tag Helper Attributes
사용enabled
특성 유형Attribute Type | 예제Examples | 기본Default |
---|---|---|
부울Boolean | true , false true , false |
true |
enabled
는 캐시 태그 도우미로 묶인 콘텐츠가 캐시되었는지 확인합니다.enabled
determines if the content enclosed by the Cache Tag Helper is cached. 기본값은 true
입니다.The default is true
. false
로 설정하면 렌더링된 출력이 캐시되지 않습니다.If set to false
, the rendered output is not cached.
예제:Example:
<cache enabled="true">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
expires-onexpires-on
특성 유형Attribute Type | 예Example |
---|---|
DateTimeOffset |
@new DateTime(2025,1,29,17,02,0) |
expires-on
은 캐시된 항목의 절대 만료 날짜를 설정합니다.expires-on
sets an absolute expiration date for the cached item.
다음 예제는 2025년 1월 29일 오후 5시 2분이 될 때까지 캐시 태그 도우미의 콘텐츠를 캐시합니다.The following example caches the contents of the Cache Tag Helper until 5:02 PM on January 29, 2025:
<cache expires-on="@new DateTime(2025,1,29,17,02,0)">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
expires-afterexpires-after
특성 유형Attribute Type | 예Example | 기본Default |
---|---|---|
TimeSpan |
@TimeSpan.FromSeconds(120) |
20분20 minutes |
expires-after
는 콘텐츠를 캐시할 첫 번째 요청 시간부터 시간 길이를 설정합니다.expires-after
sets the length of time from the first request time to cache the contents.
예제:Example:
<cache expires-after="@TimeSpan.FromSeconds(120)">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
Razor 보기 엔진은 기본 expires-after
값을 20분으로 설정합니다.The Razor View Engine sets the default expires-after
value to twenty minutes.
expires-slidingexpires-sliding
특성 유형Attribute Type | 예Example |
---|---|
TimeSpan |
@TimeSpan.FromSeconds(60) |
캐시 항목 값이 액세스되지 않는 경우 캐시 항목을 제거해야 하는 시간을 설정합니다.Sets the time that a cache entry should be evicted if its value hasn't been accessed.
예제:Example:
<cache expires-sliding="@TimeSpan.FromSeconds(60)">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
vary-by-headervary-by-header
특성 유형Attribute Type | 예제Examples |
---|---|
문자열String | User-Agent , User-Agent,content-encoding User-Agent , User-Agent,content-encoding |
vary-by-header
는 값이 변경되면 캐시 새로 고침을 트리거하는 쉼표로 구분된 헤더 값 목록을 허용합니다.vary-by-header
accepts a comma-delimited list of header values that trigger a cache refresh when they change.
다음 예제에서는 헤더 값 User-Agent
를 모니터링합니다.The following example monitors the header value User-Agent
. 이 예제는 웹 서버에 제공된 모든 User-Agent
에 대한 콘텐츠를 캐시합니다.The example caches the content for every different User-Agent
presented to the web server:
<cache vary-by-header="User-Agent">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
vary-by-queryvary-by-query
특성 유형Attribute Type | 예제Examples |
---|---|
문자열String | Make , Make,Model Make , Make,Model |
vary-by-query
는 나열된 키 값이 변경될 때 캐시 새로 고침을 트리거하는 쿼리 문자열(Query)에 쉼표로 구분된 Keys 목록을 허용합니다.vary-by-query
accepts a comma-delimited list of Keys in a query string (Query) that trigger a cache refresh when the value of any listed key changes.
다음 예제에서는 Make
및 Model
값을 모니터링합니다.The following example monitors the values of Make
and Model
. 이 예제는 웹 서버에 제공된 모든 Make
및 Model
에 대한 콘텐츠를 캐시합니다.The example caches the content for every different Make
and Model
presented to the web server:
<cache vary-by-query="Make,Model">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
vary-by-routevary-by-route
특성 유형Attribute Type | 예제Examples |
---|---|
문자열String | Make , Make,Model Make , Make,Model |
vary-by-route
는 경로 데이터 매개 변수 값이 변경되면 캐시 새로 고침을 트리거하는 쉼표로 구분된 경로 매개 변수 이름 목록을 허용합니다.vary-by-route
accepts a comma-delimited list of route parameter names that trigger a cache refresh when the route data parameter value changes.
예제:Example:
Startup.cs:Startup.cs:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{Make?}/{Model?}");
Index.cshtml:Index.cshtml:
<cache vary-by-route="Make,Model">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
vary-by-cookievary-by-cookie
특성 유형Attribute Type | 예제Examples |
---|---|
문자열String | .AspNetCore.Identity.Application , .AspNetCore.Identity.Application,HairColor .AspNetCore.Identity.Application , .AspNetCore.Identity.Application,HairColor |
vary-by-cookie
는 쿠키 값이 변경되면 캐시 새로 고침을 트리거하는 쉼표로 구분된 쿠키 이름 목록을 허용합니다.vary-by-cookie
accepts a comma-delimited list of cookie names that trigger a cache refresh when the cookie values change.
다음 예제에서는 ASP.NET Core ID와 연결된 쿠키를 모니터링합니다.The following example monitors the cookie associated with ASP.NET Core Identity. 사용자가 인증되면 ID 쿠키가 변경될 때 캐시 새로 고침이 트리거됩니다.When a user is authenticated, a change in the Identity cookie triggers a cache refresh:
<cache vary-by-cookie=".AspNetCore.Identity.Application">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
vary-by-uservary-by-user
특성 유형Attribute Type | 예제Examples | 기본Default |
---|---|---|
부울Boolean | true , false true , false |
true |
vary-by-user
는 로그인한 사용자(또는 컨텍스트 보안 주체)가 변경되면 캐시를 다시 설정해야 하는지 여부를 지정합니다.vary-by-user
specifies whether or not the cache resets when the signed-in user (or Context Principal) changes. 현재 사용자를 요청 컨텍스트 보안 주체라고도 하며 @User.Identity.Name
을 참조하여 Razor 보기에서 볼 수 있습니다.The current user is also known as the Request Context Principal and can be viewed in a Razor view by referencing @User.Identity.Name
.
다음 예에서는 현재 로그인한 사용자를 모니터링하여 캐시 새로 고침을 트리거합니다.The following example monitors the current logged in user to trigger a cache refresh:
<cache vary-by-user="true">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
이 특성을 사용하면 로그인 및 로그아웃 주기 동안 콘텐츠가 캐시에 유지됩니다.Using this attribute maintains the contents in cache through a sign-in and sign-out cycle. 값이 true
로 설정되면 인증 주기로 인해 인증된 사용자의 캐시가 무효화됩니다.When the value is set to true
, an authentication cycle invalidates the cache for the authenticated user. 사용자가 인증되면 새로운 고유 쿠키 값이 생성되므로 캐시가 무효화됩니다.The cache is invalidated because a new unique cookie value is generated when a user is authenticated. 쿠키가 없거나 만료된 경우 캐시는 익명 상태로 유지됩니다.Cache is maintained for the anonymous state when no cookie is present or the cookie has expired. 사용자가 인증되지 않으면 캐시가 유지됩니다.If the user is not authenticated, the cache is maintained.
vary-byvary-by
특성 유형Attribute Type | 예Example |
---|---|
문자열String | @Model |
vary-by
는 캐시되는 데이터의 사용자 지정을 허용합니다.vary-by
allows for customization of what data is cached. 특성의 문자열 값에서 참조하는 개체가 변경되면 캐시 태그 도우미의 콘텐츠가 업데이트됩니다.When the object referenced by the attribute's string value changes, the content of the Cache Tag Helper is updated. 종종 모델 값의 문자열 연결이 이 특성에 할당됩니다.Often, a string-concatenation of model values are assigned to this attribute. 실제로 연결된 값을 업데이트하면 캐시가 무효화되는 경우가 있습니다.Effectively, this results in a scenario where an update to any of the concatenated values invalidates the cache.
다음 예제에서는 보기를 렌더링하는 컨트롤러 메서드가 두 경로 매개 변수 myParam1
및 myParam2
의 정수 값을 합산하고, 합계를 단일 모델 속성으로 반환합니다.The following example assumes the controller method rendering the view sums the integer value of the two route parameters, myParam1
and myParam2
, and returns the sum as the single model property. 이 합계가 변경되면 캐시 태그 도우미의 콘텐츠가 다시 렌더링 및 캐시됩니다.When this sum changes, the content of the Cache Tag Helper is rendered and cached again.
작업:Action:
public IActionResult Index(string myParam1, string myParam2, string myParam3)
{
int num1;
int num2;
int.TryParse(myParam1, out num1);
int.TryParse(myParam2, out num2);
return View(viewName, num1 + num2);
}
Index.cshtml:Index.cshtml:
<cache vary-by="@Model">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
prioritypriority
특성 유형Attribute Type | 예제Examples | 기본Default |
---|---|---|
CacheItemPriority |
High , Low , NeverRemove , Normal High , Low , NeverRemove , Normal |
Normal |
priority
는 기본 제공 캐시 공급자에게 캐시 제거 지침을 제공합니다.priority
provides cache eviction guidance to the built-in cache provider. 웹 서버는 메모리가 부족할 경우 가장 먼저 Low
캐시 항목을 제거합니다.The web server evicts Low
cache entries first when it's under memory pressure.
예제:Example:
<cache priority="High">
Current Time Inside Cache Tag Helper: @DateTime.Now
</cache>
priority
특성은 특정 수준의 캐시 보존을 보장하지 않습니다.The priority
attribute doesn't guarantee a specific level of cache retention. CacheItemPriority
는 권장 사항일 뿐입니다.CacheItemPriority
is only a suggestion. 이 특성을 NeverRemove
로 설정해도 캐시된 항목이 항상 보존된다는 보장은 없습니다.Setting this attribute to NeverRemove
doesn't guarantee that cached items are always retained. 자세한 내용은 추가 리소스 섹션의 항목을 참조하세요.See the topics in the Additional Resources section for more information.
캐시 태그 도우미는 메모리 캐시 서비스에 따라 달라집니다.The Cache Tag Helper is dependent on the memory cache service. 서비스가 추가되지 않은 경우 캐시 태그 도우미가 서비스를 추가합니다.The Cache Tag Helper adds the service if it hasn't been added.
추가 자료Additional resources
피드백
여러분의 의견을 듣고 싶습니다. 제공하려는 유형을 선택하세요.
피드백 시스템은 GitHub 문제를 기반으로 구축되었습니다. 블로그에서 자세히 알아보세요.
피드백 로드 중...