6

I've created a class named MyLongRunningClass that contain a method bellow:

 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;
    }

From the controller this method is called with list of file to save in images directory. whenever HttpContext.Current.Server.MapPath("~//Content//images//"+file.FileName) is executed NullReferenceException thrown, and HttpContext.Current is always null. Same thing happen when I use session. I don't know whats wrong with the code.

Johann Blais
  • 9,389
  • 6
  • 45
  • 65
Suzan Haque
  • 145
  • 1
  • 1
  • 7

1 Answers1

8

It looks like you are running ProcessLongRunningAction on a separated thread.

However HttpContext.Current will return null when you are not running in the original request thread. This is explained here.

You could use it if you manually set the context on every thread you create. This is discussed on similar questions in SO, like here and here.

However, given the code in your question it would be better if you just add a parameter for the path in that method, as Johann Blais suggested. You will then resolve the path in the original request thread and pass it to that method, which can then run on a separated thread. This way your method does not depends on HttpContext.Current.

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112