Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why HttpContext.Current always null in user defined class in asp.net mvc?

Tags:

asp.net-mvc

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.

like image 883
Suzan Haque Avatar asked Mar 11 '14 10:03

Suzan Haque


Video Answer


1 Answers

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.

like image 189
Daniel J.G. Avatar answered Sep 28 '22 19:09

Daniel J.G.