ASP. NET Web API output cache reprint--output caching in ASP.

Source: Internet
Author: User

Reproduced in the original address: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

I. NuGet installation-related DLLs

Web API 2:install-package Strathweb.CacheOutput.WebApi2
Web API 1:install-package strathweb.cacheoutput

Two. Create a new ActionFilterAttribute and override the relevant method

    public class Webapioutputcacheattribute: ActionFilterAttribute
    {
       //Cache time/sec
        private int _timespan;
       //Client Cache time/sec
        Private int _clienttimespan;
       //Whether anonymous user cache
        Private BOOL _anonymousonly;
       //Cache index keys
        private String _cachekey;
       /Cache warehouse
        private static readonly ObjectCache webapicache = Memorycache.default;


Public Webapioutputcacheattribute (int timespan, int clienttimespan, BOOL anonymousonly)
{
_timespan = TimeSpan;
_clienttimespan = Clienttimespan;
_anonymousonly = anonymousonly;
}

Whether to cache
private bool _iscacheable (Httpactioncontext AC)
{
if (_timespan > 0 && _clienttimespan > 0)
{
if (_anonymousonly)
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
return false;
if (AC. Request.method = = Httpmethod.get) return true;
}
Else
{
throw new InvalidOperationException ("wrong Arguments");
}
return false;
}

Private Cachecontrolheadervalue Setclientcache ()
{
var CacheControl = new Cachecontrolheadervalue ();
CacheControl. MaxAge = Timespan.fromseconds (_clienttimespan);
CacheControl. Mustrevalidate = true;
return CacheControl;
}

method to execute before action call
Public override void OnActionExecuting (Httpactioncontext ac)
{
if (AC! = null)
{
if (_iscacheable (AC))
{
_cachekey = string. Join (":", new string[] {AC. Request.RequestUri.AbsolutePath, AC. Request.Headers.Accept.FirstOrDefault (). ToString ()});
if (Webapicache.contains (_cachekey))
{
var val = (string) webapicache.get (_cachekey);
if (val! = null)
{
Ac. Response = AC. Request.createresponse ();
Ac. Response.content = new Stringcontent (val);
var contenttype = (Mediatypeheadervalue) webapicache.get (_cachekey + ": response-ct");
if (ContentType = = null)
ContentType = new Mediatypeheadervalue (_cachekey. Split (': ') [1]);
Ac. Response.Content.Headers.ContentType = ContentType;
Ac. Response.Headers.CacheControl = Setclientcache ();
Return
}
}
}
}
Else
{
throw new ArgumentNullException ("Actioncontext");
}
}


Execute method After action call
Public override void OnActionExecuted (Httpactionexecutedcontext actionexecutedcontext)
{
if (! ( Webapicache.contains (_cachekey)))
{
var body = ActionExecutedContext.Response.Content.ReadAsStringAsync (). Result;
Webapicache.add (_cachekey, Body, DateTime.Now.AddSeconds (_timespan));
Webapicache.add (_cachekey + ": response-ct", ActionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds (_timespan));
}
if (_iscacheable (Actionexecutedcontext.actioncontext))
ActionExecutedContext.ActionContext.Response.Headers.CacheControl = Setclientcache ();
}

}

Three. The controller needs to add the cached get method to add the filter

[Webapioutputcache (120,60,false)]
public string Getshoppingcart ()
{
Return "Hello World";
}
Start, observe the break point, observe the effect. The whole process is to initialize the cache filter at startup, after the client invokes the Get method that added the filter, enters the OnActionExecuting method, determines whether there is a relevant cache present, if any, returns the result directly, if no, invokes the Controller's action, Then call the OnActionExecuted method to add the associated cache key-value pair and set the cache expiration time to return the result.

ASP. NET Web API output cache reprint--output caching in ASP.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.