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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With