检查会话变量(是否为空)会导致处理程序类中出现异常

发布于 2024-12-08 18:12:09 字数 4550 浏览 1 评论 0原文

我遇到了类似于此线程中描述的情况:
如何在 C# 中的静态方法中获取会话变量的值?

但是,这里没有静态方法(只是从 IHttpHandler 继承的类)

这是我的代码:

<%@ 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
    }
}   

if 行中(HttpContext.Current.Session["User_ID"] != null) 当会话变量为 null 时,出现以下异常:

“/”应用程序中的服务器错误。

未将对象引用设置为对象的实例。描述:安 当前网页执行期间发生未处理的异常 要求。请查看堆栈跟踪以获取有关的更多信息 错误及其在代码中的起源。

异常详细信息:System.NullReferenceException:对象引用不是 设置为对象的实例

我该如何解决这个问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒与心事 2024-12-15 18:12:09

由于通用处理程序被设计为准系统请求处理器,因此默认情况下它们不支持会话。您需要做的是使用 IRequiresSessionState 接口装饰您的处理程序类:

public class Handler : IHttpHandler, IRequiresSessionState

这会导致 ASP.NET 运行时为请求初始化会话容器。然后,您可以使用 HttpContext 中的 Session 实例。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文