2016-07-27 3 views
0

Session [ "user"]이 null 인 경우 코드 숨김으로 감지 할 수있는 페이지에서 출력 캐싱을 수행하고 캐시되지 않은 경우 5 분 동안 캐시 할 수 있습니까? (출력 캐싱이 만료되지 않음) 및 Session [ "user"] == null이 있습니다.비 세션 사용자를위한 출력 캐시 코드

로그인 사용자를 위해 캐시되므로 맞춤 출력 캐시를 사용하고 싶지 않습니다. 이렇게하면 익명의 방문자 만 캐시되고 페이지가 표시되고 로그인 한 사용자는 캐시되지 않은 캐시를 받게됩니다.

사용자가 로그인 할 때 일부 내 페이지가 다르기 때문에이 작업을 수행합니다. 크롤러와 일반 방문자가 실수로 캐싱을 트리거 한 사용자의 개인 데이터를 가져 오지 않고 원래 페이지를 보길 원합니다.

어떻게 C# 코드 뒤에이 작업을 수행 할 수 있습니까?

+0

'GetVaryByCustomString'을 사용할 수 있어야합니다. http : //blog.danielcorreia를보십시오.net/asp-net-mvc-vary-by-current-user/http://stackoverflow.com/questions/1043112/programatically-control-output-caching-disable-or-enable-cache-according-to-pa – smoksnes

+0

@smoksnes하지만이 방법은 각 사용자별로 캐시를 생성합니다. 맞습니까? –

+0

네, 맞습니다. 내 잘못이야. – smoksnes

답변

1

사용자 정의 OutputCacheProvider을 생성 할 수 있어야합니다. 당신의 Global.asax에서

:

public override string GetOutputCacheProviderName(HttpContext context) 
    { 
     bool isInSession = true; // Determine here. 
     if (isInSession) 
     { 
      return "CustomProvider"; 
     } 

     // Or by page: 
     if (context.Request.Path.EndsWith("MyPage.aspx")) 
     { 
      return "SomeOtherProvider"; 
     } 

     return base.GetOutputCacheProviderName(context); 
    } 

그런 다음 공급자 생성 : Set에서 null을 반환하여

public class SessionBasedCacheProvider : OutputCacheProvider 
{ 
    public override object Get(string key) 
    { 
     return null; // Do not cache. 
    } 

    public override object Add(string key, object entry, DateTime utcExpiry) 
    { 
     // Basically let it "fall through" since we don't want any caching. 
     return entry; 
    } 

    public override void Set(string key, object entry, DateTime utcExpiry) 
    { 
     // Basically let it "fall through" since we don't want any caching.    
    } 

    public override void Remove(string key) 
    { 
     // Basically let it "fall through" since we don't want any caching. 
    } 
} 

을, 당신은 항목을 캐시하지 않습니다.

캐시에서 지정된 항목을 식별하는 키 값이거나 지정된 항목이 캐시에 없으면 null입니다.

그리고 설정에 공급자를 추가 :

<system.web> 
    <caching> 
     <outputCache defaultProvider="AspNetInternalProvider"> 
     <providers> 
      <clear/> 
      <add name="CustomProvider" type="YourNamespace.SessionBasedCacheProvider, YourNamespace, Version=1.0.0.0, Culture=neutral"/> 
     </providers> 
     </outputCache> 
    </caching> 
</web> 

당신이 사용할 수 있어야 그것을 사용하려면. ASPX 페이지의 맨 위에 설정하면됩니다. 캐싱 할 위치에 따라 Location 특성에 유의하십시오.

https://msdn.microsoft.com/en-us/magazine/gg650661.aspx

https://msdn.microsoft.com/en-us/library/hdxfb6cy(v=vs.85).aspx

<%@ OutputCache Duration="60" VaryByParam="None" Location="Server" %> 
은 또한 당신은 항상 동일의 CacheProvider를 사용하고 항목이 캐시 여부를해야하는지가 결정하도록 할 수 있습니다.

public class CustomOutputCacheProvider : OutputCacheProvider 
{ 
    public override object Add(string key, object entry, DateTime utcExpiry) 
    { 
     // Determine if in session. 
     bool isInSession = true; 
     if (isInSession) 
     { 
      return null; 
     } 

     // Do the same custom caching as you did in your 
     // CustomMemoryCache object 
     var result = HttpContext.Current.Cache.Get(key); 

     if (result != null) 
     { 
      return result; 
     } 

     HttpContext.Current.Cache.Add(key, entry, null, utcExpiry, 
      System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); 

     return entry; 
    } 

    public override object Get(string key) 
    { 
     return HttpContext.Current.Cache.Get(key); 
    } 

    public override void Remove(string key) 
    { 
     HttpContext.Current.Cache.Remove(key); 
    } 

    public override void Set(string key, object entry, DateTime utcExpiry) 
    { 
     HttpContext.Current.Cache.Add(key, entry, null, utcExpiry, 
      System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); 
    } 
} 

코드 http://www.haneycodes.net/custom-output-caching-with-mvc3-and-net-4-0-done-right/

주에서, 내가 세션 이것을 테스트하지했지만, 이론적으로는 작동합니다. 그러나 나는 그것을 발표하기 전에 정말로 테스트 해보길 권한다. 캐싱은 ... 항상 사람이 생각하는 것보다 훨씬 어렵습니다 :(

UPDATE :. 세션 이후가 대신 쿠키를 사용할 수 있어야 사용할 수 없습니다

protected void Session_Start(object sender, EventArgs e) 
{ 
    Response.Cookies.Add(new HttpCookie("SessionCookie", "some_value")); 
} 

public override string GetOutputCacheProviderName(HttpContext context) 
{ 
    bool isInSession = true; // Determine here. 

    if (context.Request.Cookies["SessionCookie"] != null) 
    { 
     // Use your CustomProvider 
    } 

    if (isInSession) 
    { 
     return "CustomProvider"; 
    } 

    // Or by page: 
    if (context.Request.Path.EndsWith("MyPage.aspx")) 
    { 
     return "SomeOtherProvider"; 
    } 

    return base.GetOutputCacheProviderName(context); 
} 

는 그냥 삭제하는 것을 기억 쿠키를 사용하거나 어떤 방식 으로든 처리 할 수 ​​있습니다.

+0

감사합니다. 이 사용자 지정 출력 캐시를 작동 시키려면 페이지에 무엇을 넣어야합니까? –

+0

두 번째 코드 ("동일한 CacheProvider")를 사용하면 web.config에서 변경된 내용을 제거 할 수 있습니까? –

+0

답변을 업데이트했습니다. 하지만 여전히 web.config에 등록해야합니다. 그렇지 않으면 .NET은 공급자를 이름으로 찾지 않습니다. 중요한 것은' smoksnes