Custom ASP. NET output cache provider

Source: Internet
Author: User
Tags datetime httpcontext

ASP. NET 4 adds an extension to the output cache, which allows you to configure one or more custom output cache providers. The output cache provider can use any storage mechanism to store HTML content. This makes it possible for developers to create custom output cache providers for different persistence mechanisms, it can include local or remote disks, databases, cloud storage, and distributed cache engines (such as velocity and memcached.

To implement a custom output cache provider, you can create a custom output cache provider by deriving a class from the System. Web. Caching. OutputCacheProvider class. For example, the following MyOutputCacheProvider class is derived from the OutputCacheProvider class and creates a custom output cache provider, as shown in code listing:

Code List 19-5: MyOutputCacheProvider. cs

The code is as follows: Copy code

Using System;

Using System. Collections. Generic;

Using System. IO;

Using System. Linq;

Using System. Runtime. Serialization. Formatters. Binary;

Using System. Timers;

Using System. Web. Caching;

Using System. Collections. Concurrent;

Namespace _ 19_1

{

Public class MyOutputCacheProvider: OutputCacheProvider

    {

Private Timer timer;

Private string cachePath = "C: \ Cache \";

Private ConcurrentDictionary <string, DateTime>

CacheExpireList;

Private const string KEY_PREFIX = "_ outputCache _";

Public MyOutputCacheProvider ()

        {

CacheExpireList =

New ConcurrentDictionary <string, DateTime> ();

Timer = new Timer (3000 );

Timer. Elapsed + = (o, e) =>

            {

Var discardedList = from cacheItem in cacheExpireList

Where cacheItem. Value <DateTime. Now

Select cacheItem;

Foreach (var discarded in discardedList)

                {

Remove (discarded. Key );

DateTime discardedDate;

CacheExpireList. TryRemove (discarded. Key,

Out discardedDate );

                }

};

Timer. Start ();

        }

/// <Summary>

/// Add cache

/// </Summary>

/// <Param name = "key"> cache key </param>

/// <Param name = "entry"> cached object </param>

/// <Param name = "utcExpiry"> expiration time </param>

/// <Returns> return cache value </returns>

Public override object Add (string key, object entry,

DateTime utcExpiry)

        {

FileStream fs = new FileStream (

String. Format ("{0} {1}. binary", cachePath, key ),

FileMode. Create, FileAccess. Write );

BinaryFormatter formatter = new BinaryFormatter ();

Formatter. Serialize (fs, entry );

Fs. Close ();

CacheExpireList. TryAdd (key, utcExpiry. ToLocalTime ());

Return entry;

        }

/// <Summary>

/// Obtain the cache value

/// </Summary>

/// <Param name = "key"> cache key </param>

/// <Returns> cache value </returns>

Public override object Get (string key)

        {

String path =

String. Format ("{0} {1}. binary", cachePath, key );

If (File. Exists (path ))

            {

FileStream fs = new FileStream (

Path, FileMode. Open, FileAccess. Read );

BinaryFormatter formatter = new BinaryFormatter ();

Object result = formatter. Deserialize (fs );

Fs. Close ();

Return result;

            }

Else

            {

Return null;

            }

        }

/// <Summary>

/// Remove the cache based on the key

/// </Summary>

/// <Param name = "key"> cache key </param>

Public override void Remove (string key)

        {

String path =

String. Format ("{0} {1}. binary", cachePath, key );

If (File. Exists (path ))

            {

File. Delete (path );

            }

        }

/// <Summary>

/// Set cache

/// </Summary>

/// <Param name = "key"> cache key </param>

/// <Param name = "entry"> cached object </param>

/// <Param name = "utcExpiry"> expiration time </param>

Public override void Set (string key, object entry,

DateTime utcExpiry)

        {

String path =

String. Format ("{0} {1}. binary", cachePath, key );

FileStream fs = new FileStream (

Path, FileMode. Create, FileAccess. Write );

BinaryFormatter formatter = new BinaryFormatter ();

Formatter. Serialize (fs, entry );

Fs. Close ();

CacheExpireList. TryAdd (key, utcExpiry. ToLocalTime ());

        }

    }

}


In the MyOutputCacheProvider class, we overwrite the Add, Get, Remove, and Set methods of the OutputCacheProvider class, and Cache the page output to the "C: \ Cache \" folder.

After defining the MyOutputCacheProvider class, you can configure the provider in the Web. config file by using the new providers section of the OutputCache element, as shown in the following example:

The code is as follows: Copy code

<Caching>

<OutputCache defaultProvider = "AspNetInternalProvider">

<Providers>

<Add name = "MyOutputCacheProvider"

Type = "_ 19_1.MyOutputCacheProvider, 19-1"/>

</Providers>

</OutputCache>

</Caching>


By default, all HTTP responses, generated webpages, and controls in ASP. NET 4 use the memory output cache. The defaultProvider attribute is set to AspNetInternalProvider by default. Of course, you can change the default output cache provider used in Web applications by specifying a different provider name for defaultProvider. The following code is used:

The code is as follows: Copy code

<Caching>

<OutputCache defaultProvider = "MyOutputCacheProvider">

<Providers>

<Add name = "MyOutputCacheProvider"

Type = "_ 19_1.MyOutputCacheProvider, 19-1"/>

</Providers>

</OutputCache>

</Caching>


In addition, you can select different output cache providers for each control and each request. The simplest way to select different output cache providers for different Web user controls is to declare the new ProviderName attribute in the user control commands.

Next, we will define the output cache provider in the MyOutputCacheProviderUserControl user control, as shown in the following code:

The code is as follows: Copy code

<% @ Control Language = "C #" AutoEventWireup = "true"
CodeBehind = "MyOutputCacheProviderUserControl. ascx. cs"
Inherits = "_ 19_1.MyOutputCacheProviderUserControl" %>
<% @ OutputCache Duration = "30" VaryByParam = "none" ProviderName = "MyOutputCacheProvider" %>
<Asp: Label ID = "Label1" runat = "server"/>
The MyOutputCacheProviderUserControl. ascx. cs code is as follows:

    

Public partial class MyOutputCacheProviderUserControl: System. Web. UI. UserControl
{
Protected void Page_Load (object sender, EventArgs e)
    {
This. Label1.Text = DateTime. Now. ToLongTimeString ();
    }
}


After the MyOutputCacheProviderUserControl user control is defined, we will continue to define a test page named MyOutputCacheProviderWebForm. aspx. The code is as follows:

    

The code is as follows: Copy code

<% @ Page Language = "C #" AutoEventWireup = "true"

CodeBehind = "MyOutputCacheProviderWebForm. aspx. cs"
Inherits = "_ 19_1.MyOutputCacheProviderWebForm" %>
<% @ Register src = "MyOutputCacheProviderUserControl. ascx"
Tagname = "MyOutputCacheProviderUserControl" tagprefix = "uc1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: Button ID = "Button1" runat = "server" Text = "Refresh page"/>
<Br/>
MyOutputCacheProviderUserControl:
<Uc1: MyOutputCacheProviderUserControl ID = "MyOutputCacheProviderUserControl1" runat = "server"/>
<Br/>
MyOutputCacheProviderWebForm
<Asp: Label ID = "Label1" runat = "server" Text = "Label"> </asp: Label>
</Div>
</Form>
</Body>
</Html>
The MyOutputCacheProviderWebForm. aspx. cs code is as follows:

Public partial class MyOutputCacheProviderWebForm:

System. Web. UI. Page

{

Protected void Page_Load (object sender, EventArgs e)

    {

This. Label1.Text = DateTime. Now. ToLongTimeString ();

    }

}


Run the MyOutputCacheProviderWebForm. aspx page. The result is shown in figure 19-5:

 

Figure 19-5: sample running result

Open the "C: \ Cache \" folder and you will be able to see the generated Cache file, as shown in figures 19-6 and 19-7:

 

Figure 19-6: cache files generated on the local disk

 

Figure 19-7: cached file content

Note that you can only specify the ProviderName attribute of the @ OutputCache command in the user control, but you cannot specify the ProviderName attribute of the @ OutputCache command on the ASPX page. Because the defaultProvider configured in web. config is used by default on the page.

Although you cannot specify the ProviderName attribute of the @ OutputCache command in a declared manner, you can. the asax file uses the GetOutputCacheProviderName (HttpContext context) method to specify which provider is used for a specific request programmatically. The following code is used: public override string GetOutputCacheProviderName (HttpContext context)

The code is as follows: Copy code
{
If (context. Request. Path. EndsWith ("MyOutputCacheProviderWebForm. aspx "))
    {
Return "MyOutputCacheProvider ";
    }
Else
    {
Return base. GetOutputCacheProviderName (context );
    }
}

With the expansion of the output cache provider added in ASP. NET 4, you can now adopt more active and intelligent output cache policies for your Web site. For example, you can cache the pages with the top 10 users in a website to the memory, and cache those pages with the lowest traffic to the disk.

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.