Dav*_*vid 16 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"设置......有什么方法可以解决这个问题吗?
谢谢
Jac*_*hea 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");
}
Max*_*oro 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;
   }
}
| 归档时间: | 
 | 
| 查看次数: | 3626 次 | 
| 最近记录: |