简体   繁体   English

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

[英]ASP.net cache ASHX file server-side

Given the generic handler:给定通用处理程序:

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

}

With the code you've provided you're telling the end user browser to cache the results for 30 minutes, so you aren't doing any server side caching. 使用您提供的代码,您告诉最终用户浏览器将结果缓存30分钟,因此您不进行任何服务器端缓存。

If you want to cache the results server side you're probably looking for HttpRuntime.Cache . 如果要缓存结果服务器端,您可能正在寻找HttpRuntime.Cache This would allow you to insert an item into a cache that is globally available. 这将允许您将项目插入到全局可用的缓存中。 Then on the page load you would want to check the existence of the cached item, then if the item doesn't exist or is expired in the cache, go to the database and retrieve the objects. 然后在页面加载时,您需要检查缓存项目是否存在,然后如果项目不存在或在缓存中过期,请转到数据库并检索对象。

EDIT 编辑

With your updated code sample, I found https://stackoverflow.com/a/6234787/254973 which worked in my tests. 通过更新的代码示例,我发现https://stackoverflow.com/a/6234787/254973在我的测试中有效。 So in your case you could do: 所以在你的情况下你可以这样做:

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);
        }
    }
}

For multiple query string parameters 对于多个查询字符串参数

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 does not use Max Age to cache anything as it is not HTTP PROXY. IIS不使用Max Age来缓存任何内容,因为它不是HTTP PROXY。

That is because you are not setting Last Modified Date Time of some dependent file. 这是因为您没有设置某个相关文件的上次修改日期时间。 IIS needs a cache dependency (file dependency, so that it can check the last update time) and compare it with cache. IIS需要缓存依赖项(文件依赖项,以便它可以检查上次更新时间)并将其与缓存进行比较。 IIS does not work as HTTP Proxy, so it will not cache items for 30 seconds, instead IIS only updates cache based on some sort of date time or some cache variable. IIS不能用作HTTP代理,因此它不会将项目缓存30秒,而是IIS仅根据某种日期时间或某些缓存变量更新缓存。

You can add cache dependency two says, File Dependency and Sql Cache Dependency. 您可以添加两个缓存依赖项,即File Dependency和Sql Cache Dependency。

How dynamic caching works in IIS, lets say you have an html file. 动态缓存如何在IIS中工作,假设你有一个html文件。 IIS considers a static html text as cachable file and it will gzip it and put cached copy in its cache. IIS将静态html文本视为可缓存文件,它将对其进行gzip并将缓存副本放入其缓存中。 If last update time for static html is older then cache time, then it will use cache. 如果静态html的上次更新时间早于缓存时间,那么它将使用缓存。 If the file was modified, IIS will find that last update time of html is greater then cache time, so it will reset the cache. 如果文件被修改,IIS将发现html的最后更新时间大于缓存时间,因此它将重置缓存。

For dynamic content, you have to plan your caching accordingly. 对于动态内容,您必须相应地规划缓存。 If you are serving a content based on some row stored in SQL table, then you should keep track of last update time on that row and add cache dependency on IIS along with SQL to query the last update time of item you are trying to cache. 如果基于存储在SQL表中的某些行提供内容,则应跟踪该行的上次更新时间,并在IIS上添加缓存依赖项以及SQL以查询您尝试缓存的项目的上次更新时间。

To cache file, such as .js, .css or other you need to put it to the context.cache.要缓存文件,例如 .js、.css 或其他文件,您需要将其放入 context.cache。 Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM