c# - 使用 session 将数据从 .aspx 文件传递​​到 .ashx 文件

标签 c# asp.net .net session

实际上,我正在尝试将数据从 .aspx 发送到 .ashx 文件。我在 .aspx 中使用 Session 并试图在 .ashx 中获取 session 的值,但它显示异常::未将对象引用设置为对象的实例。

这是我的代码:-

.aspx代码

[WebMethod(enableSession:true)]
public static string SetId(string Id)
{
    HttpContext.Current.Session["MId"] = Id.ToString(); Console.Write(" ");
    string session = HttpContext.Current.Session["MId"].ToString(); // Here I am getting value

    //string session = HttpContext.Current.Session["MId"].ToString();
    //BatchReadEmails.EmailProperties session = new BatchReadEmails.EmailProperties();
    //session.MailId = Id.ToString();

    return "Ok";
}

我正在字符串 session 中获取值。
.ashx 代码:-

 public class ChangeLogHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
            {

                public void ProcessRequest(HttpContext context)
            {
                HttpRequest request = context.Request;
                HttpResponse response = context.Response;
                  string session = "";

                if (context.Session["MId"] != null)
                    session = context.Session["MId"].ToString();
                else
                    session = "Hello India";


            }
            }

这里显示的是 session = "Hello India"

我的问题:-

  1. 有什么方法可以将数据从 .aspx 文件发送到 .ashx 文件吗?

  2. 我检查了很多链接都使用 if 表示 null 但我已经检查了 .aspx 文件它在那里显示值但在 .ashx 文件中显示 null 为什么? (对于特殊情况,我们可以使用/编写 if 条件,但我已经检查过字符串 session 是否有值(value)。

我是不是错过了什么??谢谢

这些是我已经使用过的链接:-

How to access Session in .ashx file?
Accessing context session variables in c#

最佳答案

在您要添加 Session["MId"] 的 aspx 中。在 ashx 中,您正在阅读 Session["MailId"]

使您使用的键相同。 (即 MIdMailId,但不能同时使用)。

建议你定义一个常量来定义这个值,因为它是共享的,这样你就可以避免这样的问题。

关于c# - 使用 session 将数据从 .aspx 文件传递​​到 .ashx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20901714/

相关文章:

c# - QueryStringConverter 因未知原因不工作

C# 控制台/CLI 解释器?

c# - Razor View : Minify text with three dots and show full text with tooltip

c# - 在另一个创建的方法中停止对象的正确方法是什么?

c# - 在 404/500/任何异常上显示 MVC5 中的自定义错误 CSHTML 页面?

c# - 从 PHP 到 ASP.net/C#?

.net - 响应式(Reactive)扩展 : Throttle/Sample with varying interval

c# - 命令行参数

asp.net - ASP.NET MVC jQuery Ajax错误/异常处理

C# ListView 图片图标大小