获取Handler.ashx文件中的会话值

时间:2014-09-11 17:28:53

标签: asp.net vb.net handler

我正在尝试从我项目中的FileSystemHandler.ashx获取会话值,但它没有返回任何内容。

'This is the relevant line of code
Dim str As String = DirectCast(_context.Request.QueryString("SessionID"),String)

以下是方法:

Public Sub ProcessRequest(ByVal context__1 As HttpContext) Implements IHttpHandler.ProcessRequest
        Context = context__1
        
        If Context.Request.QueryString("path") Is Nothing Then
            Exit Sub
        End If

        'Get the SessionState
        Dim str As String = DirectCast(_context.Request.QueryString("SessionID"),String)

        Initialize()
        
        Dim virtualPathToFile As String = Context.Server.HtmlDecode(Context.Request.QueryString("path"))
        Dim physicalPathToFile As String = ""

        For Each mappedPath As KeyValuePair(Of String, String) In mappedPathsInConfigFile
            If virtualPathToFile.ToLower().StartsWith(mappedPath.Key.ToLower()) Then
                ' Build the physical path to the file ;
                physicalPathToFile = virtualPathToFile.Replace(mappedPath.Key, mappedPath.Value).Replace("/", "\")
                
                ' Break the foreach loop
                Exit For
            End If
        Next
        
        'The docx files are downloaded
        If Path.GetExtension(physicalPathToFile).Equals(".docx", StringComparison.CurrentCultureIgnoreCase) Then
            ' Handle .docx files ;
            Me.WriteFile(physicalPathToFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Context.Response)
        End If
        
        If Path.GetExtension(physicalPathToFile).Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) Then
            ' Handle .jpg files ;
            WriteFile(physicalPathToFile, "image/jpeg", Context.Response)
        End If
        
        ' "txt/html" is the default value for the Response.ContentType property
        ' Do not download the file. Open in the window
        Context.Response.WriteFile(physicalPathToFile)
    End Sub

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.SessionState
Imports System.Collections.Generic
Imports System.Xml
Imports DispatchSoftware
Imports System.IO

 Public Class FileSystemHandler
        Implements IHttpHandler
#Region "IHttpHandler Members"

    Private pathToConfigFile As String = "~/Incidents/MappingFile.mapping"
    **Private _context As HttpContext
    Private m_IncidentPath As String = Nothing
    Private m_SessionID As String
    Private Property Context() As HttpContext
        Get
            Return _context
        End Get
        Set(ByVal value As HttpContext)
            _context = value
        End Set
    End Property**
    
    Dim _itemHandlerPath As String
    Dim mappedPathsInConfigFile As Dictionary(Of String, String)

    Private Sub Initialize()

        If Not String.IsNullOrEmpty(Me.Context.Request.QueryString("SessionID")) Then
            m_SessionID = Me.Context.Request.QueryString("SessionID")
        End If


        If Not String.IsNullOrEmpty(Sessions.GetKeyValueSessionFile(m_SessionID, "IRPicturesPath")) Then
            m_IncidentPath = (Sessions.GetKeyValueSessionFile(m_SessionID, "IRPicturesPath"))
        End If

        Dim configFile As New XmlDocument()
        Dim physicalPathToConfigFile As String = Context.Server.MapPath(Me.pathToConfigFile)
        configFile.Load(physicalPathToConfigFile)
        ' Load the configuration file
        Dim rootElement As XmlElement = configFile.DocumentElement

        Dim handlerPathSection As XmlNode = rootElement.GetElementsByTagName("genericHandlerPath")(0)
        ' get all mappings ;
        Me._itemHandlerPath = handlerPathSection.InnerText

        Me.mappedPathsInConfigFile = New Dictionary(Of String, String)()
        Dim mappingsSection As XmlNode = rootElement.GetElementsByTagName("Mappings")(0)
        ' get all mappings ;
        For Each mapping As XmlNode In mappingsSection.ChildNodes
            Dim virtualPathAsNode As XmlNode = mapping.SelectSingleNode("child::VirtualPath")
            Dim physicalPathAsNode As XmlNode = mapping.SelectSingleNode("child::PhysicalPath")
            Me.mappedPathsInConfigFile.Add(PathHelper.RemoveEndingSlash(virtualPathAsNode.InnerText, "/"c), PathHelper.RemoveEndingSlash(physicalPathAsNode.InnerText, "\"c))
        Next
    End Sub

2 个答案:

答案 0 :(得分:2)

您必须告诉ASP.NET该处理程序需要SessionState。在您的处理程序上实现IRequiresSessionState接口:

Public Class FileSystemHandler
    Implements IHttpHandler
    ' Note that IReadOnlySessionState will give you read access.
    '  This one seems to fit your current needs best, as you are not modifying SessionState.
    Implements IReadOnlySessionState 
    ' Note that IRequiresSessionState will give you read and SAFE write access
    'Implements IRequiresSessionState

  Private ReadOnly Property Session as HttpSessionState
    Get
       Return HttpContext.Current.Session
    End Get
  End Property

  '   ... and the rest of your code.

  ' sample method:
  Private Sub Test()
     Dim myValue As Object = Session("mykey")
  End Sub

End Class

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate(v=vs.110).aspx

答案 1 :(得分:0)

将文件发送到客户端以供下载的处理程序的完整示例如下所示:

Imports System.IO
Imports System.Web
Imports System.Web.Services

Public Class DownloadAnImage
    Implements System.Web.IHttpHandler, IReadOnlySessionState

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim accessLevel = CStr(context.Session("accessLevel"))
        Dim srcDir = "~/photos"

        If accessLevel = "full" Then
            ' adjust path to other images
        End If

        Dim fname = context.Request.QueryString("filename")
        Dim actualFile = Path.Combine(context.Server.MapPath(srcDir), fname) & ".jpg"

        If File.Exists(actualFile) Then
            context.Response.ContentType = "application/octet-stream"
            context.Response.AddHeader("content-disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
            context.Response.TransmitFile(actualFile)
        Else
            context.Response.Clear()
            context.Response.StatusCode = 404
            context.Response.Write("<html><head><title>File not found</title><style>body {font-family: Arial,sans-serif;}</style></head><body><h1>File not found</h1><p>Sorry, that file is not available for download.</p></body></html>")
            context.Response.End()

        End If

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

(简称实际工作代码。)

请注意,一旦声明Implements IReadOnlySessionState,您就可以轻松访问会话状态。