简体   繁体   中英

Output Caching By Url (Route) ASP.NET 4

I haven't found a clear answer to this, so can someone help me?

If we have a URL like this

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

Then we can set

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

But I use routing, so my url looks like this:

 www.website.com/buy/houses/alaska

or for example

 www.website.com/rent/condominiums/nevada

How do I use the RouteValues in VaryByParam, or can I set it from code-behind or how? I am not using MVC, this is an ASP.NET website

Edit: (For non ASP.NET MVC apps)

How about this:

Make the OutputCache definition this:


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

In the Global.asax.cs add these methods:


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();
}

Old Content:

If you simply put OutputCache on your action method and make all your route parts part of your action method, something like this:


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

The the framework will automatically vary the cache by these items for you (See: http://aspalliance.com/2035_Announcing_ASPNET_MVC_3_Release_Candidate_2_.4 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM