加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 为什么HttpContext.Current在asp.net mvc中的用

发布时间:2020-12-15 21:07:31 所属栏目:asp.Net 来源:网络整理
导读:我创建了一个名为MyLongRunningClass的类,它包含一个方法: public string ProcessLongRunningAction(IEnumerableHttpPostedFileBase files,string id) { int currentIndex = 0; foreach (HttpPostedFileBase file in files) { currentIndex++; lock(syncRoo
我创建了一个名为MyLongRunningClass的类,它包含一个方法:
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;
    }

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

解决方法

看起来您在一个单独的线程上运行ProcessLongRunningAction.

但是,当您未在原始请求线程中运行时,HttpContext.Current将返回null.这是explained here.

如果在创建的每个线程上手动设置上下文,则可以使用它.这在SO中的类似问题上进行了讨论,如here和here.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读