【问题标题】:Output Caching By Url (Route) ASP.NET 4按 URL(路由)ASP.NET 4 的输出缓存
【发布时间】:2012-05-21 03:23:58
【问题描述】:

我还没有找到一个明确的答案,所以有人可以帮助我吗?

如果我们有这样的网址

 www.website.com/results.aspx?listingtype=2&propertytype=1&location=alaska

然后我们可以设置

 <%@ OutputCache Duration="120" VaryByParam="listingtype;propertytype;location" %>

但是我使用路由,所以我的网址是这样的:

 www.website.com/buy/houses/alaska

例如

 www.website.com/rent/condominiums/nevada

如何使用 VaryByParam 中的 RouteValues,或者我可以从代码隐藏或如何设置它? 我没有使用 MVC,这是一个 ASP.NET 网站

【问题讨论】:

    标签: c# asp.net caching routing


    【解决方案1】:

    编辑:(对于非 ASP.NET MVC 应用)

    这个怎么样:

    使 OutputCache 定义如下:

    
    <%@ OutputCache Duration="120" VaryByParam="None" VaryByCustom="listingtype;propertytype;location" %>
    

    在 Global.asax.cs 添加这些方法:

    
    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom == "lisingtype")
        {
            return GetParamFromRouteData("listingtype", context);
        }
    
        if (custom == "propertytype")
        {
            return GetParamFromRouteData("propertytype", context);
        }
    
        if (custom == "location")
        {
            return GetParamFromRouteData("location", context);
        }
    
        return base.GetVaryByCustomString(context, custom);
    }
    
    private string GetParamFromRouteData(string routeDataKey, HttpContext context)
    {
        object value;
    
        if (!context.Request.RequestContext.RouteData.Values.TryGetValue(routeDataKey, out value))
        {
            return null;
        }
    
        return value.ToString();
    }
    

    旧内容:

    如果您只是将 OutputCache 放在您的操作方法上,并使您的所有路由部分成为您操作方法的一部分,则如下所示:

    
    [OutputCache]
    public ActionResult FindProperties(string listingtype, string propertytype, string location)
    {
    }
    

    框架会根据这些项目自动为您改变缓存(参见:http://aspalliance.com/2035_Announcing_ASPNET_MVC_3_Release_Candidate_2_.4

    【讨论】:

    • 我认为这只适用于 MVC 应用程序。我的是一个 ASP.NET 网站
    • @Jesper 是的,当然可以,抱歉我错过了
    • @Jesper 更新了上面的答案,最终可能会有所帮助
    • 这非常好:) 它运行良好。页面在第二次请求时加载速度提高 5-6 倍。非常感谢。
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多