1

I'm running hangfire background process. Now part of the function being called is using MediaService which also needs HttpContext because when I try to execute mediaService.Save(media) it throws an error of

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

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

From what I was reading it needs to be a normal http request and not a background process.

How can we fake or fix the httpcontext issue inside my background service?

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);
        }
}
MadzQuestioning
  • 3,341
  • 8
  • 45
  • 76

1 Answers1

0

You will have to find a way to serialize the HttpContext that you are trying to use in your Hangfire background job. HTTP request scope is not passed as argument when you run a method (with HttpContext or most of its component) in Hangfire. Since methods are serialized and then executed outside of the HTTP request scope, you will have to find a different way to fake the HttpContext in your methods.

See here for an example on how to create a fake HttpContext in your methods that are executed by Hangfire..

Another post from Hangfire Developer on what you can do to get "some" of the properties from HttpContext by deserializing it before the job execution.

Jawad
  • 11,028
  • 3
  • 24
  • 37