为什么HttpContext.Current在asp.net mvc中的用户定义类中始终为null?

Suz*_*que 6 asp.net-mvc

我创建了一个名为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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*.G. 8

它看起来像是ProcessLongRunningAction在一个单独的线程上运行.

但是HttpContext.Current,如果未在原始请求线程中运行,则将返回null.这在这里解释.

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

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