ASP.NET MVC:OutputCache的问题

时间:2009-11-18 11:16:25

标签: asp.net asp.net-mvc outputcache

对于我当前的项目,有必要生成动态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”设置......有什么方法可以解决这个问题吗?

由于

3 个答案:

答案 0 :(得分:20)

您可以使用在缓存发生后执行的自己的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");
}

答案 1 :(得分:12)

这可能是ASP.NET MVC中的一个错误。 在内部,他们有一个名为OutputCachedPage的类型,派生自Page。在OnResultExecuting上调用OutputCacheAttribute时,他们会创建此类型的实例并调用ProcessRequest(HttpContext.Current),最终调用SetIntrinsics(HttpContext context, bool allowAsync)来设置ContentType,如下所示:

HttpCapabilitiesBase browser = this._request.Browser;
this._response.ContentType = browser.PreferredRenderingMime;

这是一个修复:

public sealed class CacheAttribute : OutputCacheAttribute {

   public override void OnResultExecuting(ResultExecutingContext filterContext) {

      string contentType = null;
      bool notChildAction = !filterContext.IsChildAction;

      if (notChildAction) 
         contentType = filterContext.HttpContext.Response.ContentType;

      base.OnResultExecuting(filterContext);

      if (notChildAction)
         filterContext.HttpContext.Response.ContentType = contentType;
   }
}

答案 2 :(得分:-1)

尝试设置VaryByContentEncoding以及VaryByParam。