programing

전체 ASP에 대해 브라우저 캐시를 비활성화합니다.NET 웹사이트

megabox 2023. 5. 4. 19:48
반응형

전체 ASP에 대해 브라우저 캐시를 비활성화합니다.NET 웹사이트

나는 전체 ASP에 대해 브라우저 캐시를 비활성화하는 방법을 찾고 있습니다.NET MVC 웹사이트

다음 방법을 찾았습니다.

Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.Cache.SetNoStore();

또한 메타 태그 방법(일부 MVC 작업은 헤드 없이 Ajax를 통해 부분 HTML/JSON을 보내기 때문에 저에게는 효과가 없습니다.)

<meta http-equiv="PRAGMA" content="NO-CACHE">

하지만 전체 웹 사이트에 대해 브라우저 캐시를 비활성화할 수 있는 간단한 방법을 찾고 있습니다.

IActionFilter에서 상속되는 클래스를 만듭니다.

public class NoCacheAttribute : ActionFilterAttribute
{  
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

그런 다음 필요한 곳에 속성을 배치합니다.

[NoCache]
[HandleError]
public class AccountController : Controller
{
    [NoCache]
    [Authorize]
    public ActionResult ChangePassword()
    {
        return View();
    }
}

자신의 것을 굴리는 대신 제공된 것을 사용하면 됩니다.

앞에서 언급했듯이 모든 항목에 대해 캐싱을 사용하지 않도록 설정하지 마십시오.예를 들어, jQuery 스크립트는 ASP에서 많이 사용됩니다.NET MVC를 캐시해야 합니다.사실 CDN을 사용하는 것이 이상적이지만, 제 요점은 콘텐츠를 캐시해야 한다는 것입니다.

여기서 [OutputCache]를 모든 곳에 뿌리는 것보다 가장 잘 작동하는 것은 클래스를 사용하는 것입니다.

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class NoCacheController  : Controller
{
}

캐시를 사용하지 않도록 설정할 모든 컨트롤러가 이 컨트롤러에서 상속됩니다.

NoCacheController 클래스에서 기본값을 재정의해야 하는 경우 작업 방법에 캐시 설정을 지정하기만 하면 작업 방법에 대한 설정이 우선합니다.

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ViewResult Index()
{
  ...
}
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();

모든 요청은 default.aspx를 통해 먼저 라우팅됩니다. 따라서 당신이 그 뒤에 코드를 입력할 수 있다고 가정합니다.

컨트롤러에 의해 렌더링된 모든 페이지(예: HTML 페이지)에 대해 브라우저 캐싱을 사용 불가능으로 설정하고 스크립트, 스타일시트 및 이미지와 같은 리소스에 대해서는 캐싱을 유지할 수 있습니다.MVC4+ 번들링 및 최소화를 사용하는 경우 스크립트 및 스타일시트의 기본 캐시 기간(시간이 아닌 고유 URL 변경에 따라 캐시가 무효화되므로 매우 긴 기간)을 유지해야 합니다.

MVC4+에서 모든 컨트롤러에서 브라우저 캐싱을 사용하지 않도록 설정하고 컨트롤러에서 제공하지 않는 경우 이를 유지하려면 다음에 추가합니다.FilterConfig.RegisterGlobalFilters:

filters.Add(new DisableCache());

정의DisableCache다음과 같이:

class DisableCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}

이 답변이 질문과 100% 관련이 없다는 것은 알지만 누군가에게 도움이 될 수도 있습니다.

전체 ASP에 대해 브라우저 캐시를 비활성화하려는 경우.NET MVC 사이트에서 일시적으로만 이 작업을 수행하려는 경우 브라우저에서 캐시를 비활성화하는 것이 좋습니다.

여기 크롬의 스크린샷이 있습니다.

이전 답변을 모두 구현했지만 여전히 제대로 작동하지 않는 뷰가 하나 있습니다.

알고 보니 제가 문제를 겪고 있던 관점의 이름은 '최근'이었습니다.분명히 이것은 인터넷 익스플로러 브라우저를 혼란스럽게 했습니다.

(컨트롤러에서) 보기 이름을 다른 이름으로 변경한 후('Recent5' 선택) 위의 솔루션이 작동하기 시작했습니다.

Global.asax 파일에서 아래 코드를 시도할 수 있습니다.

protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
        Response.Cache.SetNoStore();
    }

UI

<%@ OutPutCache Location="None"%>
<%
    Response.Buffer = true;
    Response.Expires = -1;
    Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
    Response.CacheControl = "no-cache";
%>

배경

Context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Expires = -1;          
Response.Cache.SetNoStore();

언급URL : https://stackoverflow.com/questions/1160105/disable-browser-cache-for-entire-asp-net-website

반응형