Asp.net

ASP.NET MVC:OutputCache 的問題

  • January 6, 2012

對於我目前的項目,有必要生成動態 CSS ……

所以,我有一個部分視圖,它用作 CSS 傳遞器……控制器程式碼如下所示:

   [OutputCache(CacheProfile = "DetailsCSS")]
   public ActionResult DetailsCSS(string version, string id)
   {
       // Do something with the version and id here.... bla bla
       Response.ContentType = "text/css";
       return PartialView("_css");
   }

輸出記憶體配置文件如下所示:

<add name="DetailsCSS" duration="360" varyByParam="*" location="Server" varyByContentEncoding="none" varyByHeader="none" />

問題是:當我使用 OutputCache 行 ([OutputCache(CacheProfile = “DetailsCSS”)]) 時,響應的內容類型是“text/html”,而不是“text/css”…當我刪除它時,它按預期工作……

所以,對我來說,OutputCache 似乎沒有在這裡保存我的“ContentType”設置……有什麼辦法解決這個問題嗎?

謝謝

您可以使用在記憶體發生後執行的您自己的 ActionFilter 覆蓋 ContentType。

public class CustomContentTypeAttribute : ActionFilterAttribute
{
   public string ContentType { get; set; }

   public override void OnResultExecuted(ResultExecutedContext filterContext)
   {
       filterContext.HttpContext.Response.ContentType = ContentType;
   }
}

然後在 OutputCache 之後呼叫該屬性。

[CustomContentType(ContentType = "text/css", Order = 2)]
[OutputCache(CacheProfile = "DetailsCSS")]
public ActionResult DetailsCSS(string version, string id)
{
   // Do something with the version and id here.... bla bla
   return PartialView("_css");
}

或者(我還沒有嘗試過)但是用 CSS 特定的實現覆蓋“OutputCacheAttribute”類。像這樣的東西…

public class CSSOutputCache : OutputCacheAttribute
{
   public override void OnResultExecuting(ResultExecutingContext filterContext)
   {
       base.OnResultExecuting(filterContext);
       filterContext.HttpContext.Response.ContentType = "text/css";
   }
}

和這個…

[CSSOutputCache(CacheProfile = "DetailsCSS")]
public ActionResult DetailsCSS(string version, string id)
{
   // Do something with the version and id here.... bla bla
   return PartialView("_css");
}

引用自:https://stackoverflow.com/questions/1755313