Is not a valid udi - when saving media using content service

The following code successfully creates a node that references a media item. Everything looks as in intended in the back-office. However, in my view I get the following exception.

String “5317” is not a valid udi.

if I save and published each node via the back-office, then the view renders as expected. I recall that I need to flush the cached. What am i doing wrong here?

        private void Save()
    {
        var contentService = ApplicationContext.Current.Services.ContentService;
        var content = contentService.CreateContent("testnode", 1234, "docType");

        
        content.SetValue("summary", "hello world");

		if (!string.IsNullOrEmpty(mediaUrl))
		{
			var media = CreateMedia(tweet, _twitterMedia.Id, mediaUrl);
			if (media != null)
			{
				content.SetValue("image", media.Id);
			}
		}

        contentService.SaveAndPublishWithStatus(content, 0, false);
    }

    private Umbraco.Core.Models.IMedia CreateMedia(int mediaId, string mediaUrl)
    {
        var mediaService = ApplicationContext.Current.Services.MediaService;
        var request = WebRequest.Create(mediaUrl);
        var webResponse = request.GetResponse();
        var responseStream = webResponse.GetResponseStream();
        Umbraco.Core.Models.IMedia media = null;
        if (responseStream != null)
        {
            var originalImage = new Bitmap(responseStream);
            var path = HttpContext.Current.Server.MapPath("~/App_Data/TempImage/test.jpg");
            originalImage.Save(path, ImageFormat.Jpeg);
            using (FileStream fileStream = new FileStream(path, FileMode.Open))
            {
                var fileName = fileStream.Name;
                var mediaImage = mediaService.CreateMedia(tweet.Id.ToString(), mediaId, "image");
                mediaImage.SetValue("umbracoFile", fileName, fileStream);
                mediaService.Save(mediaImage);                    
                responseStream.Dispose();
                webResponse.Dispose();
                originalImage.Dispose();
                media = mediaService.GetById(mediaImage.Id);
                mediaService.RebuildXmlStructures(mediaImage.Id);
            }
           
        }
        return media;
    }

This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/89518-is-not-a-valid-udi-when-saving-media-using-content-service