ASP.net缓存ASHX文件服务器端

本文关键字:文件 服务器端 ASHX 缓存 net ASP | 更新日期: 2023-09-27 18:22:02

给定通用处理程序:

<%@ WebHandler Language="C#" Class="autocomp" %>
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
public class autocomp : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";
        context.Response.BufferOutput = true;
        var searchTerm = (context.Request.QueryString["name_startsWith"] + "").Trim();
        context.Response.Write(searchTerm);
        context.Response.Write(DateTime.Now.ToString("s"));
        context.Response.Flush();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

如何根据name_startsWith查询字符串参数server side缓存此文件1小时?有了网络用户控制,它很容易:

<%@ OutputCache Duration="120" VaryByParam="paramName" %>

但我已经四处寻找了一段时间来对通用处理程序(ashx)文件进行同样的处理,但找不到任何解决方案。

ASP.net缓存ASHX文件服务器端

使用您提供的代码,您将告诉最终用户浏览器缓存结果30分钟,这样就不会进行任何服务器端缓存。

如果你想缓存结果服务器端,你可能正在寻找HttpRuntime.Cache。这将允许您将项目插入全局可用的缓存中。然后在页面加载时,您希望检查缓存项的存在,然后如果该项在缓存中不存在或已过期,则转到数据库并检索对象。

编辑

通过您更新的代码示例,我发现https://stackoverflow.com/a/6234787/254973这在我的测试中起到了作用。所以在你的情况下,你可以做:

public class autocomp : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        OutputCachedPage page = new OutputCachedPage(new OutputCacheParameters
        {
            Duration = 120,
            Location = OutputCacheLocation.Server,
            VaryByParam = "name_startsWith"
        });
        page.ProcessRequest(HttpContext.Current);
        context.Response.ContentType = "application/json";
        context.Response.BufferOutput = true;
        var searchTerm = (context.Request.QueryString["name_startsWith"] + "").Trim();
        context.Response.Write(searchTerm);
        context.Response.Write(DateTime.Now.ToString("s"));
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private sealed class OutputCachedPage : Page
    {
        private OutputCacheParameters _cacheSettings;
        public OutputCachedPage(OutputCacheParameters cacheSettings)
        {
            // Tracing requires Page IDs to be unique.
            ID = Guid.NewGuid().ToString();
            _cacheSettings = cacheSettings;
        }
        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            InitOutputCache(_cacheSettings);
        }
    }
}

对于多个查询字符串参数

public class test : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        OutputCachedPage page = new OutputCachedPage(new OutputCacheParameters
        {
            Duration = 120,
            Location = OutputCacheLocation.Server,
            VaryByParam = "name;city"
        });
        page.ProcessRequest(HttpContext.Current);
        context.Response.ContentType = "application/json";
        context.Response.BufferOutput = true;
        var searchTerm = (context.Request.QueryString["name"] + "").Trim();
        var searchTerm2 = (context.Request.QueryString["city"] + "").Trim();
        context.Response.Write(searchTerm+" "+searchTerm2+" ");
        context.Response.Write(DateTime.Now.ToString("s"));
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private sealed class OutputCachedPage : Page
    {
        private OutputCacheParameters _cacheSettings;
        public OutputCachedPage(OutputCacheParameters cacheSettings)
        {
            // Tracing requires Page IDs to be unique.
            ID = Guid.NewGuid().ToString();
            _cacheSettings = cacheSettings;
        }
        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            InitOutputCache(_cacheSettings);
        }
    }
}

IIS不使用最大年龄缓存任何内容,因为它不是HTTP代理。

这是因为您没有设置某个依赖文件的"上次修改日期时间"。IIS需要缓存依赖项(文件依赖项,以便检查上次更新时间),并将其与缓存进行比较。IIS不起HTTP代理的作用,因此在30秒内不会缓存项目,相反,IIS仅根据某种日期时间或某些缓存变量更新缓存。

您可以添加缓存依赖项,如文件依赖项和Sql缓存依赖项。

动态缓存在IIS中是如何工作的,比如说您有一个html文件。IIS将静态html文本视为可缓存文件,它将对其进行gzip处理,并将缓存的副本放入其缓存中。若静态html的最后更新时间比缓存时间早,那个么它将使用缓存。如果文件被修改,IIS将发现html的上次更新时间大于缓存时间,因此它将重置缓存。

对于动态内容,您必须相应地规划缓存。如果您提供的内容基于存储在SQL表中的某一行,那么您应该跟踪该行的上次更新时间,并在IIS上添加缓存依赖项和SQL,以查询您试图缓存的项目的最后更新时间。

要缓存文件,如.js、.css或其他文件,需要将其放入context.cache。示例:

    public void ProcessRequest(HttpContext context)
    {
        var cachedResult = context.Cache.Get(context.Request.Path);
        if (cachedResult != null && cachedResult.GetType() == typeof(VueFileRequestResult))
        {
            RequestedFileResponce(context, cachedResult as VueFileRequestResult);
            return;
        }
        
        // SOME ACTIONS WITH NON-CACHED FILE
        var fileContent = System.IO.File.ReadAllBytes(filePath);
        var result = new VueFileRequestResult(contentType.GetDescription(), fileContent);
        RequestedFileResponce(context, result);
        var expirationDate = DateTime.Now.AddYears(1);
        var dependency = new CacheDependency(filePath);
        context.Cache.Add(context.Request.Path, result, dependency, expirationDate, TimeSpan.Zero, CacheItemPriority.Low, null);
        return;
    }