Programming

전체 ASP.NET 웹 사이트에 대해 브라우저 캐시를 사용하지 않도록 설정

procodes 2020. 5. 8. 21:38
반응형

전체 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">

그러나 전체 웹 사이트에서 브라우저 캐시를 비활성화하는 간단한 방법을 찾고 있습니다.


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를 통해 먼저 라우팅되므로 코드를 뒤에 넣을 수 있다고 가정합니다.


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();
    }
}

자신을 굴리는 대신 제공된 것을 사용하십시오.

앞에서 언급했듯이 모든 캐싱을 비활성화하지 마십시오. 예를 들어 ASP.NET MVC에서 많이 사용되는 jQuery 스크립트는 캐시되어야합니다. 실제로 이상적으로는 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()
{
  ...
}

You may want to disable browser caching for all pages rendered by controllers (i.e. HTML pages), but keep caching in place for resources such as scripts, style sheets, and images. If you're using MVC4+ bundling and minification, you'll want to keep the default cache durations for scripts and stylesheets (very long durations, since the cache gets invalidated based on a change to a unique URL, not based on time).

In MVC4+, to disable browser caching across all controllers, but retain it for anything not served by a controller, add this to FilterConfig.RegisterGlobalFilters:

filters.Add(new DisableCache());

Define DisableCache as follows:

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

I know this answer is not 100% related to the question, but it might help someone.

If you want to disable the browser cache for the entire ASP.NET MVC Website, but you only want to do this TEMPORARILY, then it is better to disable the cache in your browser.

Here's a screenshot in Chrome


I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.


You can try below code in Global.asax file.

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";
%>

Background

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

반응형