1

I have a situation like the one described in this thread:
How can i get the value of a session variable inside a static method in c#?

However, there are no static methods here (just a class inherited from IHttpHandler)

Here is my code:

<%@ WebHandler Language="C#" Class="Telerik.Web.Examples.FileExplorer.FilterAndDownloadFiles.Handler" %>

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text;
using Telerik.Web.UI;

namespace Telerik.Web.Examples.FileExplorer.FilterAndDownloadFiles
{
    [RadCompressionSettings(HttpCompression = CompressionType.None)] // Disable RadCompression for this page ;
    public class Handler : IHttpHandler
    {
        #region IHttpHandler Members

        private HttpContext _context;
        private HttpContext Context
        {
            get
            {
                return _context;
            }
            set
            {
                _context = value;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            Context = context;
            string filePath = context.Request.QueryString["path"];
            filePath = context.Server.MapPath(filePath);

            if (filePath == null)
            {
                return;
            }

            System.IO.StreamReader streamReader = new System.IO.StreamReader(filePath);
            System.IO.BinaryReader br = new System.IO.BinaryReader(streamReader.BaseStream);

            byte[] bytes = new byte[streamReader.BaseStream.Length];

            br.Read(bytes, 0, (int)streamReader.BaseStream.Length);

            if (bytes == null)
            {
                return;
            }

            streamReader.Close();
            br.Close();
            string fileName = System.IO.Path.GetFileName(filePath);
            string MimeType = GetMimeType(fileName);
            string extension = System.IO.Path.GetExtension(filePath);
            char[] extension_ar = extension.ToCharArray();
            string extension_Without_dot = string.Empty;
            for (int i = 1; i < extension_ar.Length; i++)
            {
                extension_Without_dot += extension_ar[i];
            }

            //if (extension == ".jpg")
            //{ // Handle *.jpg and
            //    WriteFile(bytes, fileName, "image/jpeg jpeg jpg jpe", context.Response);
            //}
            //else if (extension == ".gif")
            //{// Handle *.gif
            //    WriteFile(bytes, fileName, "image/gif gif", context.Response);
            //}
        if (HttpContext.Current.Session["User_ID"] != null)
        {
            WriteFile(bytes, fileName, MimeType + " " + extension_Without_dot,      context.Response);
        }

        }

        /// <summary>
        /// Sends a byte array to the client
        /// </summary>
        /// <param name="content">binary file content</param>
        /// <param name="fileName">the filename to be sent to the client</param>
        /// <param name="contentType">the file content type</param>
        private void WriteFile(byte[] content, string fileName, string contentType, HttpResponse response)
        {
            response.Buffer = true;
            response.Clear();
            response.ContentType = contentType;

            response.AddHeader("content-disposition", "attachment; filename=" + fileName);

            response.BinaryWrite(content);
            response.Flush();
            response.End();
        }

        private string GetMimeType(string fileName)
        {
            string mimeType = "application/unknown";
            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();
            return mimeType;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion
    }
}   

In the line of if (HttpContext.Current.Session["User_ID"] != null) I get the following exception when session variable is null :

Server Error in '/' Application.

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object

How can I fix this?

Community
  • 1
  • 1
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • It looks like you're passing the context into the method. Have you tried using that context instead? Also, have you considered using a nullable parameter and passing the session value into the method from the calling method? – James Johnson Oct 07 '11 at 20:28
  • hi dear james / i have some javascript codes that use this handler / i want to check session value inside handler / but i had the upper error... – SilverLight Oct 07 '11 at 20:41
  • See the answer from @Matthew Abbott. That should take care of the problem – James Johnson Oct 07 '11 at 20:45

2 Answers2

5

Because generic handlers are designed to be barebone request processors, they do not by default support Session. What you need to do, is decorate your handler class with the IRequiresSessionState interface:

public class Handler : IHttpHandler, IRequiresSessionState

This causes the ASP.NET runtime to initialise the session container for the request. You can then use the Session instance from your HttpContext.

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • +1 Nice and simple. Does that interface implement any methods OP needs to be aware of? – James Johnson Oct 07 '11 at 20:30
  • @JamesJohnson - No, it is a marker interface only, the handler needs to just be decorated with the interface and the runtime takes care of the rest. – Matthew Abbott Oct 07 '11 at 20:32
  • @Matthew Abbott thanks for answer / but couses another error -> Compiler Error Message: CS1722: Base class 'IRequireSessionState' must come before any interfaces – SilverLight Oct 07 '11 at 20:37
  • `IRequiresSessionState` is an interface, not a class. Can you update your question with your revised `Handler` class declaration? – Matthew Abbott Oct 07 '11 at 20:39
  • @Matthew Abbott thanks for attention / but my entire class is in my Q ... i have some javascript codes that use Handler.ashx file inside my project / in this file (i pasted entire codes in my Q) i want to check my session variable! – SilverLight Oct 07 '11 at 20:46
  • I mean, update your question to include the change you've made to include `IRequiresSessionState` – Matthew Abbott Oct 07 '11 at 20:48
1

http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • Don't post only a link as an aswer. At least write something, or post the link as a comment. Fix it and I'll upvote it. – James Johnson Oct 07 '11 at 20:32