【问题标题】:How can I cache customerror page using outputcache如何使用 outputcache 缓存自定义错误页面
【发布时间】:2015-12-03 18:48:01
【问题描述】:

如何使用 outputcache 缓存自定义错误页面?

自定义错误页面:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/customerror/notfound" responseMode="ExecuteURL" />
  <remove statusCode="500" subStatusCode="-1" />
  <error statusCode="500" path="/customerror/servererror" responseMode="ExecuteURL" />
</httpErrors>

自定义错误控制器:

public class CustomErrorController
{

    [OutputCache(Duration = duration, Location = OutputCacheLocation.Server, VaryByHeader = "Host", VaryByParam = "None")]
    public ActionResult NotFound()
    {
        return this.View("NotFound", this.Build());
    }

    private TestModel Build()
    {
        var model = new TestModel
                        {
                            Header = GetSiteHeaderContent(SiteId),
                            Footer = GetSiteFooterContent(SiteId),
                            Navigations = GetNavigations(),
                            SecondaryNavigations = GetSecondaryNavigation()
                        };
        return model;
    }
}

问题是动作从未被缓存,尽管我在很多地方都使用了输出缓存并且工作正常。

注意:我使用的是 Memcached。

提前致谢。

【问题讨论】:

    标签: asp.net caching asp.net-mvc-5 memcached


    【解决方案1】:

    可能的方法是重定向到另一个动作并缓存它,比如

    public ActionResult Index()
    {
        return RedirectToAction("NotFound");
    }
    
    [OutputCache]
    public ActionResult NotFound()
    {
        return this.View("NotFound", this.Build());
    }
    
    private TestModel Build()
    {
        var model = new TestModel
                        {
                            Header = GetSiteHeaderContent(SiteId),
                            Footer = GetSiteFooterContent(SiteId),
                            Navigations = GetNavigations(),
                            SecondaryNavigations = GetSecondaryNavigation()
                        };
        return model;
    }
    

    【讨论】:

    • 但如果您使用redirectToAction,那么Response.StatusCode 将从404 更改。这不是一个好习惯。您为应该返回 404 错误的 url 返回了无效的状态代码。
    【解决方案2】:

    这是因为 ASP.NET 输出缓存仅在请求以 200 状态代码响应时起作用。

    另请参阅ASP.NET MVC OutputCache for HTTP 503 status code,它在 503 响应中存在类似问题。

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多