发布图像时“ await httpClient.PostAsync”上的对象处置实例

时间:2018-11-02 13:14:06

标签: c# ios xamarin

嗨,我在Xamarin的MultipartFormDataContent中添加以下代码时得到了ObjectDisposedException

JToken jobectImages = rootObject["Images"];

                foreach (var item in jobectImages)
                {
                    foreach (var internalitem in item)
                    {
                        foreach (var imageGroup in internalitem)
                        {
                            foreach (JObject image in imageGroup)
                            {
                                string sFileName = "";
                                string sFile2 = "";

                                try
                                {
                                    sFileName = image.GetValue("FileName").ToString();
                                    sFile2 = image.GetValue("FilePath").ToString();
                                }
                                catch
                                {
                                    sFileName = "";
                                    sFile2 = "";
                                }

                                if (sFile2 != "" && File.Exists(sFile2))
                                {
                                    StreamContent s = await Imagestream(sFile2);
                                    if (s != null)
                                    {
                                        multipartContent.Add(s, sFileName, sFileName);
                                    }
                                }
                            }
                        }
                    }
                }

下面是我的图像流方法

public async Task<StreamContent> Imagestream(String FilePath)
        {
            StreamContent streamContent2 = null;
            if (File.Exists(FilePath))
            {
                FileStream fs2 = File.OpenRead(FilePath);
                streamContent2 = new StreamContent(fs2);
                streamContent2.Headers.Add("Content-Type", "application/octet-stream");
            }
            return streamContent2;
        }

在此行获取错误

var response = await httpClient.PostAsync(GlobalVariables.url, multipartContent).ConfigureAwait(false);

在此之前,我还使用上面的Imagestream方法向MultipartFormDataContent添加了另一张图像...任何帮助将非常感谢

1 个答案:

答案 0 :(得分:0)

原来是我的StreamContent(),在分配给MultipartFormDataContent之前它已被自动处置。要解决此问题,我使用了以下

 MemoryStream memoryStream = new MemoryStream();
                    streamContent.Position = 0;
                    streamContent.CopyTo(memoryStream);
                    memoryStream.Position = 0;
                    StreamContent content = new StreamContent(memoryStream);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");


            multipartContent.Add(content, "signature", "signature.png");