Development Tip

컨트롤러 작업 방법에 대한 출력 캐시를 프로그래밍 방식으로 지우는 방법

yourdevel 2020. 11. 28. 12:32
반응형

컨트롤러 작업 방법에 대한 출력 캐시를 프로그래밍 방식으로 지우는 방법


컨트롤러 작업에 작업에 지정된 OutputCache 특성이있는 경우 IIS를 다시 시작하지 않고도 출력 캐시를 지울 수있는 방법이 있습니까?

[OutputCache (Duration=3600,VaryByParam="param1;param2")]
public string AjaxHtmlOutputMethod(string param1, string param2)
{
  var someModel = SomeModel.Find( param1, param2 );

  //set up ViewData
  ...

  return RenderToString( "ViewName", someModel );
}

을 (를) 사용 HttpResponse.RemoveOutputCacheItem(string path)하여 지우고 있지만 작업 방법에 매핑하는 경로가 무엇인지 파악하는 데 문제가 있습니다. ViewName에서 렌더링 한 aspx 페이지로 다시 시도하겠습니다.

아마도 난 그냥 수동으로의 출력을 삽입 할 수 있습니다 RenderToStringHttpContext.Cache나는이 일을 알아낼 수없는 경우 대신.

최신 정보

OutputCache는 VaryByParam이고 하드 코딩 된 경로 "/ controller / action"을 테스트해도 실제로 outputcache가 지워지지 않으므로 "/ controller / action / param1 / param2"와 일치해야하는 것처럼 보입니다.

그 말은 아마 오브젝트 레벨 캐싱으로 되돌아 수동의 출력을 캐시해야합니다 RenderToString():(


이 시도

var urlToRemove = Url.Action("AjaxHtmlOutputMethod", "Controller");
HttpResponse.RemoveOutputCacheItem(urlToRemove);

업데이트 :

var requestContext = new System.Web.Routing.RequestContext(
    new HttpContextWrapper(System.Web.HttpContext.Current),
    new System.Web.Routing.RouteData());

var Url = new System.Web.Mvc.UrlHelper(requestContext);

업데이트 :

이 시도:

[OutputCache(Location= System.Web.UI.OutputCacheLocation.Server, Duration=3600,VaryByParam="param1;param2")]

그렇지 않으면 사용자 컴퓨터에 HTML 출력을 캐시했기 때문에 캐시 삭제가 작동하지 않습니다.


허용되는 답변 외에도 VaryByParam 매개 변수를 지원하려면 다음을 수행하십시오.

  [OutputCache (Duration=3600, VaryByParam="param1;param2", Location = OutputCacheLocation.Server)]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       object routeValues = new { param1 = param1, param2 = param2 };

       string url = Url.Action("AjaxHtmlOutputMethod", "Controller", routeValues);

       Response.RemoveOutputCacheItem(url);
  }

그러나 Egor의 대답은 모든 OutputCacheLocation 값을 지원하기 때문에 훨씬 좋습니다.

  [OutputCache (Duration=3600, VaryByParam="param1;param2")]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       if (error)
       {
           Response.Cache.SetNoStore(); 
           Response.Cache.SetNoServerCaching();
       }
  }

SetNoStore ()SetNoServerCaching ()가 호출, 그들은 현재 요청이 캐시되는 것을 방지한다. 해당 요청에 대해 함수가 호출되지 않는 한 추가 요청은 캐시됩니다.

이는 오류 상황을 처리하는 데 이상적입니다. 일반적으로 응답을 캐시하고 싶지만 오류 메시지가 포함 된 경우에는 그렇지 않습니다.


올바른 흐름은 다음과 같습니다.

filterContext.HttpContext.Response.Cache.SetNoStore()

Another option is to use VaryByCustom for the OutputCache and handle the invalidation of certain cache elements there.

Maybe it works for you, but it's not a general solution to your problem


Add code to AjaxHtmlOutputMethod

HttpContext.Cache.Insert("Page", 1);
Response.AddCacheItemDependency("Page");

To clear output cache you can now use

HttpContext.Cache.Remove("Page");

참고URL : https://stackoverflow.com/questions/1167890/how-to-programmatically-clear-outputcache-for-controller-action-method

반응형