是ASP中的DiskCacheProvider.Net 4.0真的存在



我在很多地方看到说ASP.net 4.0的新特性,代码是:

    <caching>
        <outputCache defaultProvider="AspNetInternalProvider">
            <providers>
                <add name="DiskCache"
                    type="test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>
            </providers>
        </outputCache>
    </caching>

无论如何,我不能让它工作,我改变了代码从内到外,没有用。我只能从微软找到一个缓存提供程序,与asp.net一起发布的是AspNetInternalProvider

所以,DiskOutputCacheProvider真的存在吗?是,如何使用

另外,我需要在Azure中使用它,所以我猜这里必须有一个地方用于磁盘缓存来设置缓存文件夹,对吗?

如果有人有azure的磁盘缓存解决方案(使用LocalResources)。本地存储或不),请与我分享,免费或付费。谢谢。

DiskCacheOutputProvider不包含在。net 4.0中。但是你可以扩展。net 4.0缓存并创建你自己的缓存。网上有一些关于如何做到这一点的例子。

http://weblogs.asp.net/scottgu/archive/2010/01/27/extensible -输出缓存- - asp -网- 4 - vs - 2010和-网- 4 - 0 - series.aspx

您正在寻找的实现可以在这里找到

** https://web.archive.org/web/20161107101740/http://aspnet.4guysfromrolla.com/code/ExtensibleOutputCachingDemo.zip **来源https://web.archive.org/web/20211020121627/https://www.4guysfromrolla.com/articles/061610-1.aspx

这只是示例代码,还没有准备好,所以要小心使用它。你必须在web.config中把它们连接起来。

// Based on code by 'Scott Mitchell' <mitchell@4guysfromrolla.com>
// http://www.4guysfromrolla.com/articles/061610-1.aspx
// Add the following to Web.config
// Use the cacheFolder attribute to specify the disk location for the cache
//
// <system.web>
//    <caching>
//       <outputCache enableOutputCache="true" defaultProvider="disk">
//          <providers>
//             <add name="disk" type="DiskOutputCache.DiskOutputCacheProvider, DiskOutputCache" cacheFolder="~/App_Data/OutputCache" />
//          </providers>
//       </outputCache>
//    </caching>
// </system.web> 
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web;
using System.Web.Caching;
namespace DiskOutputCache {
   /// <summary>
   /// An <see cref="OutputCacheProvider"/> that uses the file system for storage.
   /// </summary>
   public class DiskOutputCacheProvider : OutputCacheProvider {
      readonly IDictionary<string, CacheItem> cacheItems = new ConcurrentDictionary<string, CacheItem>();
      string cacheFolder;
      public override void Initialize(string name, NameValueCollection config) {
         HttpServerUtility serverUtil = HttpContext.Current.Server;
         const string cacheFolderKey = "cacheFolder";
         string cacheFolderValue = config[cacheFolderKey];
         string folder;
         if (!String.IsNullOrEmpty(cacheFolderValue)) {
            folder = serverUtil.MapPath(cacheFolderValue);
            config.Remove(cacheFolderKey);
         } else {
            throw new ArgumentException(String.Format("The attribute '{0}' is missing in the configuration of the '{1}' provider.", cacheFolderKey, name));
         }
         if (folder[folder.Length - 1] != Path.DirectorySeparatorChar)
            folder += Path.DirectorySeparatorChar;
         if (!Directory.Exists(folder))
            Directory.CreateDirectory(folder);
         this.cacheFolder = folder;
         base.Initialize(name, config);
      }
      public override object Add(string key, object entry, DateTime utcExpiry) {
         // See if this key already exists in the cache. If so, we need to return it and NOT overwrite it!
         object results = Get(key);
         if (results != null)
            return results;
         // If the item is NOT in the cache, then save it!
         Set(key, entry, utcExpiry);
         return entry;
      }
      public override object Get(string key) {
         CacheItem item;
         if (!this.cacheItems.TryGetValue(key, out item))
            return null;
         if (item.UtcExpiry < DateTime.UtcNow) {
            // Item has expired
            Remove(key, item);
            return null;
         }
         return GetCacheData(item);
      }
      object GetCacheData(CacheItem item) {
         string fileToRetrieve = GetFilePath(item);
         BinaryFormatter formatter = new BinaryFormatter();
         Stream source = null;
         try {
            source = new FileStream(fileToRetrieve, FileMode.Open, FileAccess.Read, FileShare.Read);
            return formatter.Deserialize(source);
         } catch (IOException) {
         } finally {
            if (source != null)
               source.Dispose();
         }
         return null;
      }
      public override void Remove(string key) {
         CacheItem item;
         if (this.cacheItems.TryGetValue(key, out item)) 
            Remove(key, item);
      }
      void Remove(string key, CacheItem item) {
         RemoveCacheData(item);
         this.cacheItems.Remove(key);
      }
      void RemoveCacheData(CacheItem item) {
         string fileToDelete = GetFilePath(item);
         try {
            File.Delete(fileToDelete);
         } catch (IOException) { }
      }
      public override void Set(string key, object entry, DateTime utcExpiry) {
         // Create a DiskOutputCacheItem object
         CacheItem item = new CacheItem(key, utcExpiry);
         WriteCacheData(item, entry);
         // Add item to CacheItems, if needed, or update the existing key, if it already exists
         this.cacheItems[key] = item;
      }
      void WriteCacheData(CacheItem item, object entry) {
         string fileToWrite = GetFilePath(item);
         BinaryFormatter formatter = new BinaryFormatter();
         Stream destination = null;
         try {
            destination = new FileStream(fileToWrite, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            formatter.Serialize(destination, entry);
         } catch (IOException) {
         } finally {
            if (destination != null)
               destination.Dispose();
         }
      }
      string GetFilePath(CacheItem item) {
         return this.cacheFolder + item.FileName;
      }
      class CacheItem {
         static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();
         public string FileName { get; private set; }
         public DateTime UtcExpiry { get; private set; }
         public CacheItem(string key, DateTime utcExpiry) {
            this.FileName = GetSafeFileName(key);
            this.UtcExpiry = utcExpiry;
         }
         string GetSafeFileName(string unsafeFileName) {
            char[] invalid = unsafeFileName.ToCharArray()
               .Where(c => invalidFileNameChars.Contains(c))
               .ToArray();
            if (invalid.Length > 0) {
               var sb = new StringBuilder(unsafeFileName, unsafeFileName.Length);
               for (int i = 0; i < invalid.Length; i++) 
                  sb.Replace(invalid[i], '_');
               return sb.ToString(); 
            }
            return unsafeFileName;
         }
      }
   }
}

最新更新