【问题标题】:ASP.NET MVC Prevent OutputCache if request is from a spider如果请求来自蜘蛛,ASP.NET MVC 阻止 OutputCache
【发布时间】:2013-11-14 05:50:42
【问题描述】:

如果我收到来自 Spider 的请求,我会启动 Phantom JS 进程并返回动态 HTML。 (使用 OnExecuting 过滤器并设置 ActionResult)

但是 OutputCache 过滤器也在这个方法上,它正在妨碍!

例如:

步骤 1. 使用普通用户代理加载页面。 (输出缓存缓存 URL) 步骤 2. 使用蜘蛛用户代理加载页面。 (之前缓存的响应被发送给蜘蛛,我的 Phantom JS 过滤器永远不会运行)

【问题讨论】:

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


    【解决方案1】:

    当请求来自搜索引擎爬虫时,使用 VaryByCustom 强制“缓存未命中”。

    在你的Controller/Action

    [OutputCache(VaryByCustom="Crawler")]
    public ActionResult Index()
    {
         // ...
         return View();
    }
    

    然后在你的Global.asax:

    public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg == "Crawler" && context.Request.Browser.Crawler)
               return Guid.NewGuid().ToString();
    
        return base.GetVaryByCustomString(context, arg);
    }
    

    【讨论】:

    • 这仅适用于 OutputCacheLocation.None 或 OutputCacheLocation.Server 或 NoStore = true 至少在 MVC 5 中
    • @LostInComputer,阅读OP文字the previous cached response is sent to the spider,很明显他用的是OutputCacheLocation.Server
    • 我可能误解了这个问题。我在想如果请求者是爬虫,他想禁用服务器缓存并删除客户端缓存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    相关资源
    最近更新 更多