Access sessions in asp.net handler

asp.net, handler, session, vb.net

Solution

I completely agree with `jbl`'s comment.

- You can get and set session using `HttpContext.Current.Session` anywhere on your project.

- No matter where you create the session. Just make sure that the session exists before you access it.

- Not sure what exactly you are asking here(need some more explanation).

Here is an example, where I used session on HttpHandler. However, it is on c#(hope you can understand).

Problem

I am trying to upload images using generic handler as shown below and I have a normal aspx page where I am showing all the uploaded images after uploading.Everything is working fine. ``` <%@ WebHandler Language="VB" Class="Upload"%> Imports System Imports System.Web Imports System.Threading Imports System.Web.Script.Serialization Imports System.IO Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState Public Class FilesStatus Public Property thumbnail_url() As String Public Property name() As String Public Property url() As String Public Property size() As Integer Public Property type() As String Public Property delete_url() As String Public Property delete_type() As String Public Property [error]() As String Public Property progress() As String End Class Private ReadOnly js As New JavaScriptSerializer() Private ingestPath As String Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim r = context.Response ingestPath = context.Server.MapPath("~/UploadedImages/") r.AddHeader("Pragma", "no-cache") r.AddHeader("Cache-Control", "private, no-cache") HandleMethod(context) End Sub Private Sub HandleMethod(ByVal context As HttpContext) Select Case context.Request.HttpMethod Case "HEAD", "GET" ServeFile(context) Case "POST" UploadFile(context) Case "DELETE" DeleteFile(context) Case Else context.Response.ClearHeaders() context.Response.StatusCode = 405 End Select End Sub Private Sub DeleteFile(ByVal context As HttpContext) Dim filePath = ingestPath & context.Request("f") If File.Exists(filePath) Then File.Delete(filePath) End If End Sub Private Sub ServeFile(ByVal context As HttpContext) If String.IsNullOrEmpty(context.Request("f")) Then ListCurrentFiles(context) Else DeliverFile(context) End If End Sub Private Sub UploadFile(ByVal context As HttpContext) Dim statuses = New List(Of FilesStatus)() Dim headers = context.Request.Headers If String.IsNullOrEmpty(headers("X-File-Name")) Then UploadWholeFile(context, statuses) Else UploadPartialFile(headers("X-File-Name"), context, statuses) End If WriteJsonIframeSafe(context, statuses) End Sub Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) If context.Request.Files.Count <> 1 Then Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request") End If Dim inputStream = context.Request.Files(0).InputStream Dim fullName = ingestPath & Path.GetFileName(fileName) Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write) Dim buffer = New Byte(1023) {} Dim l = inputStream.Read(buffer, 0, 1024) Do While l > 0 fs.Write(buffer, 0, l) l = inputStream.Read(buffer, 0, 1024) Loop fs.Flush() fs.Close() End Using statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"}) End Sub Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) For i As Integer = 0 To context.Request.Files.Count - 1 Dim file = context.Request.Files(i) file.SaveAs(ingestPath & Path.GetFileName(file.FileName)) Thread.Sleep(1000) Dim fname = Path.GetFileName(file.FileName) statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"}) Next i End Sub Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) context.Response.AddHeader("Vary", "Accept") Try If context.Request("HTTP_ACCEPT").Contains("application/json") Then context.Response.ContentType = "application/json" Else context.Response.ContentType = "text/plain" End If Catch context.Response.ContentType = "text/plain" End Try Dim jsonObj = js.Serialize(statuses.ToArray()) context.Response.Write(jsonObj) End Sub Private Sub DeliverFile(ByVal context As HttpContext) Dim filePath = ingestPath & context.Request("f") If File.Exists(filePath) Then context.Response.ContentType = "application/octet-stream" context.Response.WriteFile(filePath) context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """") Else context.Response.StatusCode = 404 End If End Sub Private Sub ListCurrentFiles(ByVal context As HttpContext) Dim files = New List(Of FilesStatus)() Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly) For Each name In names Dim f = New FileInfo(name) files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"}) Next name context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""") Dim jsonObj = js.Serialize(files.ToArray()) context.Response.Write(jsonObj) context.Response.ContentType = "application/json" End Sub Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class ``` Now I want to add a session variable by generating a random string and add the uploaded images to the newly created random string. 1.I have seen this Question on SO to use `System.Web.SessionState.IRequiresSessionState` for sessions and how do I `create` a `folder` with that and add my images to that folder after doing that how do I `access` this session variable in my `normal` `aspx` page. 2.(Or) the better way is create session variable in aspx page and pass that to handler?If so how can I do that? 3 .I am trying to find the control from my handler.Is that possible?If anyone knows how to get this then also my problem will get resolved so that I am trying to create a session from m aspx page. Can anyone explain the better way of handling this situation.

Original source