【问题标题】:Why HttpContext.Current always null in user defined class in asp.net mvc?为什么 HttpContext.Current 在 asp.net mvc 中的用户定义类中始终为空?
【发布时间】:2014-03-11 10:50:01
【问题描述】:

我创建了一个名为 MyLongRunningClass 的类,其中包含以下方法:

 public string ProcessLongRunningAction(IEnumerable<HttpPostedFileBase> files ,string id)
    {
        int currentIndex = 0;

        foreach (HttpPostedFileBase file in files)
        {
            currentIndex++;
            lock(syncRoot)
            {                
             string path=HttpContext.Current.Server.MapPath("~//Content//images       //"+file.FileName);//Excecption is created here........
              file.SaveAs(path);
            }
          Thread.Sleep(300);
        }
        return id;
    }

从控制器调用此方法,并使用要保存在图像目录中的文件列表。每当HttpContext.Current.Server.MapPath("~//Content//images//"+file.FileName) 被执行时NullReferenceException 被抛出,HttpContext.Current 总是null。当我使用会话时也会发生同样的事情。我不知道代码有什么问题。

【问题讨论】:

  • 将目标路径传递给方法,有助于关注点分离。

标签: asp.net-mvc


【解决方案1】:

看起来您正在一个单独的线程上运行ProcessLongRunningAction。

但是,当您不在原始请求线程中运行时,HttpContext.Current 将返回 null。这是explained here。

如果您在创建的每个线程上手动设置上下文,则可以使用它。这在 SO 中的类似问题上进行了讨论,例如 here 和 here。

但是,鉴于您问题中的代码,如果您只是按照 Johann Blais 的建议为该方法中的路径添加一个参数会更好。然后,您将解析原始请求线程中的路径并将其传递给该方法,然后该方法可以在单独的线程上运行。这样你的方法不依赖于HttpContext.Current。

【讨论】:

  • 感谢谁给了我宝贵的建议。
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 2017-10-29
  • 2018-03-20
  • 2015-06-25
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多