2017-08-09 27 views
1
Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1. 
Response.Cache.AppendCacheExtension("no-store, must-revalidate"); 
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0. 
Response.AppendHeader("Expires", "0"); // Proxies. 

我在哪裏設置這些代碼,以便它們被添加到我的所有頁面中?我在哪裏可以在ASP.NET MVC中設置Response.AppendHeader,以便在所有頁面中添加以下標題?

感謝

+1

您可以製作自定義操作過濾器並將其附加到任何控制器或操作以應用此標頭。您可以將過濾器應用到基本控制器,並從您的所有控制器繼承此過濾器。 – Jasen

回答

2

您可以創建一個動作過濾器,並設置所需的HTTP頭的響應。您可以覆蓋OnActionExecuted並將這些新標題添加到響應中。

public class MyCustomHeadersFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     filterContext.HttpContext.Response.Headers.Add("Expires","0"); 
     filterContext.HttpContext.Response.Headers.Add("Pragma", "no-cache"); 

     base.OnActionExecuted(filterContext); 
    } 
} 

如果您希望爲所有請求提供此功能,您可以全局註冊。

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new MyCustomHeadersFilter()); 
    } 
} 

如果你想它只是一個控制器,可以應用在控制器級別,如果你需要它只是針對特定的操作方法,你可以申請它的操作方法的水平。

+0

謝謝,我已將它添加到全球 –

相關問題