为什么HttpContext.Current在ASP.NET MVC中的用户定义类中始终为null? [英] Why HttpContext.Current always null in user defined class in asp.net mvc?

查看:65
本文介绍了为什么HttpContext.Current在ASP.NET MVC中的用户定义类中始终为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为MyLongRunningClass的类,其中包含以下方法:

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

从控制器调用此方法,并带有要保存在图像目录中的文件列表.每当执行HttpContext.Current.Server.MapPath("~//Content//images//"+file.FileName)时都会抛出NullReferenceException,并且HttpContext.Current始终为null.当我使用会话时也会发生同样的事情.我不知道代码有什么问题.

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.

推荐答案

您似乎在单独的线程上运行ProcessLongRunningAction.

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

但是,当您不在原始请求线程中运行时,HttpContext.Current将返回null.这是在此处进行解释.

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

如果您在创建的每个线程上手动设置上下文,则可以使用它.关于SO中类似问题的讨论,例如此处此处.

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.

但是,考虑到问题中的代码,最好按照该方法在Johann Blais的建议中为路径添加一个参数.然后,您将解析原始请求线程中的路径,并将其传递给该方法,然后该方法可以在单独的线程上运行.这样,您的方法就不依赖于HttpContext.Current.

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.

这篇关于为什么HttpContext.Current在ASP.NET MVC中的用户定义类中始终为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆