【问题标题】:How to have HttpContext in a Background Process如何在后台进程中拥有 HttpContext
【发布时间】:2020-06-27 17:48:08
【问题描述】:

我正在运行 hangfire 后台进程。现在被调用的函数的一部分是使用 MediaService ,它也需要 HttpContext 因为当我尝试执行 mediaService.Save(media) 它会抛出一个错误

 System.ArgumentNullException
 Value cannot be null. Parameter name: httpContext

      System.ArgumentNullException: Value cannot be null.
      Parameter name: httpContext

从我阅读的内容来看,它需要是一个正常的 http 请求,而不是后台进程。

我们如何伪造或修复后台服务中的 httpcontext 问题?

public void saveMedia()
{
        var mediaService = ApplicationContext.Current.Services.MediaService;
        string[] filePaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "uploads");

        foreach (string filePath in filePaths)
        {
            using (Stream stream = System.IO.File.OpenRead(filePath))
            {
                string filename = Path.GetFileName(filePath);
                string mediaType = Constants.Conventions.MediaTypes.File;
                string ext = Path.GetExtension(filename);

                IMedia media = mediaService.CreateMedia(filename, Constants.System.Root, mediaType);
                media.SetValue("umbracoFile", filename, stream);
                mediaService.Save(media); // HTTPCONTEXT error here
                media = null;
            }

            System.IO.File.Delete(filePath);
        }
}

【问题讨论】:

  • 请不要转发您的问题。你已经有一个线程打开here
  • @Jawad 将删除其他帖子,对此感到抱歉

标签: c# .net umbraco umbraco7 hangfire


【解决方案1】:

您必须找到一种方法来序列化您尝试在 Hangfire 后台作业中使用的 HttpContext。当您在 Hangfire 中运行方法(使用 HttpContext 或其大部分组件)时,HTTP 请求范围不会作为参数传递。由于方法是序列化的,然后在 HTTP 请求范围之外执行,因此您必须找到一种不同的方法来伪造方法中的 HttpContext。

See here 举例说明如何在 Hangfire 执行的方法中创建假 HttpContext..

Another post from Hangfire Developer 关于如何在作业执行之前通过反序列化从 HttpContext 获取“一些”属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 2010-11-14
    • 2011-08-03
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多