浏览器无法使用复杂的URL从ASP.NET处理程序缓存图像

时间:2018-10-02 15:32:30

标签: asp.net webforms browser-cache httphandler

我正在尝试缓存图像,这些图像是使用ASP.NET处理程序提供的,其代码如下:

处理程序

public class ResourceHandler : IHttpHandler, IRouteHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.Private);
        context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0));

        RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData;

        string name = routeData.Values["type"].ToString();
        string imagePath = "path/{type}"

        FileInfo fileInfo = new FileInfo(imagePath);

        if (fileInfo == null)
        {
            // Resource not found
            context.Response.StatusCode = 404;
            return;
        }

        string rawIfModifiedSince = context.Request.Headers.Get("If-Modified-Since");
        if (string.IsNullOrEmpty(rawIfModifiedSince))
        {
            // Set Last Modified time
            context.Response.Cache.SetLastModified(fileInfo.LastWriteTimeUtc);
        }
        else
        {
            DateTime ifModifiedSince = DateTime.Parse(rawIfModifiedSince);

            // HTTP does not provide milliseconds, so remove it from the comparison
            if (fileInfo.LastWriteTimeUtc.AddMilliseconds(
                               -fileInfo.LastWriteTimeUtc.Millisecond) == ifModifiedSince)
            {
                // The requested file has not changed
                context.Response.StatusCode = 304;
                return;
            }
        }

        using (Stream stream = fileInfo.OpenRead())
        {
            byte[] buffer = new byte[32];
            while (stream.Read(buffer, 0, 32) > 0)
            {
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(buffer);
            }
        }
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return this;
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

}

路线

我发现路由的复杂性迫使浏览器总是从服务器请求,而不是从缓存请求。 (我尝试过很多,Chrome,Firefox,Edge)

如果我注册一条简单的路线,一切都会按预期进行:

routes.Add(new Route("image/{type}", new ResourceHandler()));

示例:

  

http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da_f8d8c2cc-271c-407e-9bbb-3deae1c577da_9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450

但是,如果URL如下所示,每个浏览器都拒绝从缓存中获取图像:

routes.Add(new Route("image/{type}/{authenticatedUserId}/{userId}/{imageid}", new ResourceHandler()));

示例:

  

http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da/f8d8c2cc-271c-407e-9bbb-3deae1c577da/9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450

我已经尝试了所有可能的标头组合,但是为什么URL是个问题?简单的一种有效,动态的一种无效。

更新

它与最新版本的Firefox兼容。

0 个答案:

没有答案