【问题标题】:No trailing slash in hostname, HttpResponse.RemoveOutputCacheItem doesn't work主机名中没有斜杠,HttpResponse.RemoveOutputCacheItem 不起作用
【发布时间】:2011-02-19 14:00:52
【问题描述】:

我在这里有点麻烦。

我有一个动作,它的输出是相当静态的,直到另一个动作用于更新第一个动作的数据源。我使用 HttpResponse.RemoveOutputCacheItem 来删除该操作的缓存输出,以便下次用户加载它时刷新它。

基本上我有这样的动作:

[OutputCache(Duration=86400, Location=OutputCacheLocation.Server)]
public ActionResult Index()
{
    return ...
}

在我的 HomeController 上,在另一个控制器上执行另一个操作,更新前者中使用的信息:

public ActionResult SaveMenu(int id, Menu menu)
{
    ...
    HttpResponse.RemoveOutputCacheItem(Url.Action("Index", "Home"));
    ...
}

疯狂的是,只要您加载 URL http://site/ 或 http://site/Home/Index,它就可以工作。当您使用 URL http://site 时,它永远不会刷新。

这是为什么呢?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 caching asp.net-mvc-2 action-filter


    【解决方案1】:

    这与OutputCacheAttribute 的工作方式有关,特别是它对RouteData 的依赖性不为空。相关部分是:

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (!filterContext.IsChildAction)
        {
            new OutputCachedPage(this._cacheSettings).ProcessRequest(HttpContext.Current);
        }
     }
    

    ResultExecutingContext filterContext 派生自 ControllerContext。这是ControllerContext.IsChildAction的来源:

    public virtual bool IsChildAction
    {
        get
        {
            RouteData routeData = this.RouteData;
            if (routeData == null)
            {
                return false;
            }
            return routeData.DataTokens.ContainsKey("ParentActionViewContext");
        }
    }
    

    那么,为什么这与您的问题有关?

    因为当您省略“/”时,您的 Route 将不匹配任何内容。默认路由是“/”。一篇更深入地解释这一点的文章在这里:http://www.58bits.com/blog/2008/09/29/ASPNet-MVC-And-Routing-Defaultaspx.aspx。编写它是为了解释为什么在 ASP.NET MVC 1 项目中需要 Default.aspx 文件,但原因在于同一个地方。

    所以,基本上,RouteData 是空的,所以 OutputCacheAttribute 不能工作。您可以按照 Michael Jasper 的建议并利用 URL 重写来解决您的问题。

    【讨论】:

    • 所以基本上,你的意思是,既然“mysite.com”不匹配任何路由,它就不会被缓存?
    • 正确...除非您使用 URLRewriting 使其成为“mysite.com/”
    【解决方案2】:

    IIS 有一个非常有用的模块,叫做 URL Rewrite。其中一个选项是删除或附加斜杠到所有/特定的 url。如果只是尾随斜杠有问题,这应该可以。

    【讨论】:

    • 但是确切地了解它发生的原因不是更有趣吗?也许这会带来更优雅或更全面的解决方案?
    • 是的,我承认我的解决方案有点宽泛的油漆刷。
    【解决方案3】:

    我在 SharePoint 的行为方式中看到了类似的行为。 SharePoint 与 http://site 混淆了;它无法确定 URL 是指向 File 还是 SharePoint Site。这里可能发生了类似的事情。

    您可能已经通过在 URL 后面附加一个斜杠解决了这个问题;但是,以防万一您还没有:

    url = string.Format( "{0}/", url.TrimEnd( '/' ) );
    

    【讨论】:

      猜你喜欢
      • 2013-01-07
      • 2012-02-16
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2011-11-01
      • 1970-01-01
      相关资源
      最近更新 更多