【发布时间】:2014-03-14 08:07:19
【问题描述】:
我正在接管一个项目,该项目使用 handler.ashx 自动生成不同大小的图像版本(如果它们尚不存在)。此外,它应该提供现有图像并将它们缓存在客户端浏览器中。但是对图像的所有请求都返回 200,因此不会缓存。
当我使用 fiddler 查看请求时,图像的初始响应显示
收到图像后的第二个请求
<%@ WebHandler Language="VB" CodeBehind="GenericHandler.ashx.vb" Class=".GenericHandler" %>
Imports System.IO
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
Imports System.Globalization
Public Class GenericHandler
Implements System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
RequestHandler(context)
End Sub
Private Sub RequestHandler(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "GET"
GetFile(context)
Case Else
context.Response.ClearHeaders()
context.Response.StatusCode = 405
End Select
End Sub
Private Sub GetFile(ByVal context As HttpContext)
Dim strAssetId As String = context.Request("asset")
Dim strSize As String = context.Request("size")
Dim fileName As String = getAssetName(strAssetId)
Dim internalFile As String = CalculateFileName(context, fileName)
Dim refresh As TimeSpan = New TimeSpan(1, 0, 0, 0) '1 day cache
Dim encode As Boolean = context.Request("encode") = "1"
'we have already created the file
If File.Exists(internalFile) Then
'has the browser already recieved a cached version
If Not String.IsNullOrEmpty(context.Request.Headers("If-Modified-Since")) Then
Dim provider As CultureInfo = CultureInfo.InvariantCulture
Dim lastMod As DateTime = DateTime.ParseExact(context.Request.Headers("If-Modified-Since"), "r", provider).ToLocalTime()
'cached but is it within the expiry range
If lastMod < DateTime.Now.Add(refresh) Then
context.Response.StatusCode = 304
Return
End If
End If
Else
'this size of image didn't exist so create it.
GenerateFile(context, internalFile)
End If
context.Response.ClearContent()
context.Response.AddHeader("Content-Disposition", "attachment; filename=""" + fileName + """")
context.Response.Cache.SetExpires(DateTime.Now.Add(refresh))
context.Response.Cache.SetMaxAge(refresh)
context.Response.Cache.SetCacheability(HttpCacheability.Public)
context.Response.Cache.SetValidUntilExpires(True)
context.Response.ContentType = "image/png"
If encode Then
context.Response.Write(ImageBase64Encoder.Encode(internalFile))
Else
context.Response.WriteFile(internalFile)
End If
End Sub
Private Function CalculateFileName(ByVal context As HttpContext, fileName)
'calculates the filename of the requestedfilesize
End Function
Private Sub GenerateFile(ByVal context As HttpContext, internalFile As String)
'generates the correct sized version of the original image
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
【问题讨论】: