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

Tom*_*len 2 c# asp.net caching

鉴于通用处理程序:

<%@ 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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

如何server side根据name_startsWith查询字符串参数缓存此文件1小时?使用Web用户控件很容易:

<%@ OutputCache Duration="120" VaryByParam="paramName" %>
Run Code Online (Sandbox Code Playgroud)

但我一直在寻找与通用handler(ashx)文件相同的一段时间,并找不到任何解决方案.

Ste*_*n V 8

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

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

编辑

通过更新的代码示例,我发现/sf/answers/436435121/在我的测试中有效.所以在你的情况下你可以这样做:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)