【问题标题】:HttpContext.Current.Session keep return Object reference not set to an instance of an object on my class (MVC 5)HttpContext.Current.Session 保持返回对象引用未设置为我的类上的对象实例(MVC 5)
【发布时间】:2017-02-12 16:55:02
【问题描述】:

我有课来保持 PowerShell 会话。这样我就可以在不创建新会话的情况下访问 powershell 会话。下面是我的sn-p代码

public class PowerShellSession : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }

    public PowerShell PowerShell2010()
    {
        if(HttpContext.Current.Session == null)
        {
            WSManConnectionInfoSession connExch = new WSManConnectionInfoSession();

            var session = connExch.GetExchangeConnectionSession(2010);

            Runspace runspace = RunspaceFactory.CreateRunspace(session);
            runspace.Open();
            PowerShell Shell = PowerShell.Create();
            Shell.Runspace = runspace;
            HttpContext.Current.Session["PowerShell2010"] = Shell;

            return Shell;
        }
        if (HttpContext.Current.Session["PowerShell2010"] != null)
        {
            WSManConnectionInfoSession connExch = new WSManConnectionInfoSession();

            var session = connExch.GetExchangeConnectionSession(2010);

            Runspace runspace = RunspaceFactory.CreateRunspace(session);
            runspace.Open();
            PowerShell Shell = PowerShell.Create();
            Shell.Runspace = runspace;
            HttpContext.Current.Session["PowerShell2010"] = Shell;

            return Shell;
        }
        else
        {
            return (PowerShell)HttpContext.Current.Session["PowerShell2010"];
        }       

    }
}

问题是当我尝试为会话设置值时,我的代码总是返回“对象引用未设置为对象的实例”。

这里是设置会话值的代码

HttpContext.Current.Session["PowerShell2010"] = Shell;

我是不是做错了什么?

【问题讨论】:

  • HttpContext.Current.Session 是字典吗?在尝试将其设置为 Shell 之前,您应该为其设置添加手表并查看值是什么。
  • 我从来没有看到你设置了会话。如果HttpContext.Current.Sessionnull,则您的第一个 if 条件进入。当您刚刚证明它是 null 时,您没有为该属性分配会话但尝试访问它

标签: asp.net-mvc powershell session asp.net-web-api


【解决方案1】:

我没有使用 Powershell 的经验。话虽如此,问题的很大一部分似乎是您的if() 语句不正确。

首先检查if(HttpContext.Current.Session == null),如果在当前上下文中找不到 Session 对象,则为 TRUE。但是随后您继续尝试使用该 Session 对象,所以难怪您会收到您遇到的错误。

下一个似乎也是错误的:if (HttpContext.Current.Session["PowerShell2010"] != null),如果先前尝试存储 Powershell 对象成功,则为 TRUE。但是随后您继续创建并存储一个新的 Powershell 对象,这完全破坏了您显然想要的缓存。您需要将其替换为 == null,假设您首先会找到访问 Session 对象的方法。

最后但并非最不重要的一点是,获得 HTTP Session 对象的机会更大:

  • 确保在您的 Web 服务器和/或 Web.Config 文件中启用了会话状态;
  • 在 MVC 控制器类中运行尽可能多的上述代码,而不是在类型库类或类似的东西中。或者使用参数将 HTTP Session 对象从 MVC 控制器操作方法传递到类型库方法。

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 2013-05-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2021-09-14
    • 2020-04-13
    相关资源
    最近更新 更多