我试图创建一个HTTPHandler来验证某些静态资源,在这种情况下是PDF文件。
我已将以下内容添加到web.config
:
<configuration>
<system.web>
<httpHandlers>
<clear />
<add path="*.pdf" verb="*" validate="true" type="AuthenticatedStaticResourceHandler" />
</httpHandlers>
</system.web>
</configuration>
这是我的HTTPHandler类:
Imports Microsoft.VisualBasic
Public Class AuthenticatedStaticResourceHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim resource As String = String.Empty
Select Case context.Request.HttpMethod
Case "GET"
resource = context.Server.MapPath(context.Request.FilePath)
If Helpers.User.CanAccessPath(context.Request.FilePath, context.User.Identity.Name) Then
SendContentTypeAndFile(context, resource)
Else
FormsAuthentication.RedirectToLoginPage()
End If
End Select
End Sub
Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private Function SendContentTypeAndFile(ByVal context As HttpContext, ByVal file As String) As HttpContext
context.Response.ContentType = GetContentType(file)
context.Response.TransmitFile(file)
context.Response.End()
Return context
End Function
Private Function GetContentType(ByVal filename As String) As String
'Used to set the encoding for the reponse stream
Dim resource As String = String.Empty
Dim file As System.IO.FileInfo = New System.IO.FileInfo(filename)
If file.Exists Then
Select Case file.Extension.Remove(0, 1).ToLower()
Case "pdf"
resource = "application/pdf"
Case "jpg"
resource = "image/jpg"
Case "gif"
resource = "image/gif"
Case "png"
resource = "image/png"
Case "css"
resource = "text/css"
Case "js"
resource = "text/javascript"
Case Else
resource = String.Empty
End Select
End If
Return IIf(resource.Length > 0, resource, Nothing)
End Function
End Class
我在Select Case context.Request.HttpMethod
的{{1}}行设置了一个断点,但是当我尝试访问ProcessRequest
时,不会触发断点。此外,尝试访问的示例PDF I埋藏在我无法访问的文件夹中,但是PDF已经提供。
这让我相信我的HTTPHandler没有被调用。
我错过了什么吗?我做错了什么?
答案 0 :(得分:1)
最有可能的是,您必须在web.config中添加一个额外的部分以支持所有版本的IIS。
对于IIS7及更高版本,您需要在system.webServer
部分注册处理程序:
<system.webServer>
<handlers>
<add ... />
</handlers>
</system.webServer>