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

I created a class called MyLongRunningClass , which contains the method below:

  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 a list of files to save in the image directory. whenever HttpContext.Current.Server.MapPath("~//Content//images//"+file.FileName) NullReferenceException , and HttpContext.Current always null . The same thing happens when I use a session. I do not know what is wrong with the code.

+6
source share
1 answer

It looks like you are using ProcessLongRunningAction in a separate thread.

However, HttpContext.Current will return null if you are not working in the original request stream. This is explained here .

You can use it if you manually set the context for each created stream. This is discussed on similar issues in SO, for example here and here .

However, given the code in your question, it would be better if you just added a parameter for the path in this method, as Johann Blays suggested. You then resolve the path in the original request thread and pass it to this method, which can then be executed in a separate thread. Thus, your method is independent of HttpContext.Current .

+8
source

All Articles