C# - 将内容复制到流时出错

C# - Error while copying content to a stream

我有这个表格,其中大约有 10 个字段,最多 10 个图像。我将它们上传到服务器,大部分时间它都能正常工作,但有时 return 出错 Error while copying content to a stream

在那之后,当我重新启动应用程序并再次尝试时,有时可以,有时却不能。

代码

// Image Path
var path_image_1 = await SecureStorage.GetAsync("image_1");

MultipartFormDataContent multiContent = new MultipartFormDataContent();
multiContent.Headers.ContentType.MediaType = "multipart/form-data";

// About 10 Fields like this
multiContent.Add(new StringContent(Email), "email");

// About 10 Images
var image_1 = File.ReadAllBytes(path_image_1);
multiContent.Add(new ByteArrayContent(image_1, 0, image_1.Count()), "images", path_image_1);


HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync(url, multiContent);
string serverResponse = await response.Content.ReadAsStringAsync();

如果它有时有效,那么重试几次可能会有帮助。如果您使用 polly nuget package, you can enclose this code in a block that will catch the exception and retry 可配置的次数和可配置的等待时间。

var policy = Policy
.Handle<HttpRequestException>()
.Retry(3, onRetry: (exception, retryCount) =>
{
   Console.WriteLine($"retry Count is: {retryCount}");
});

policy.Execute(() => DoStuff());

然后你的实际逻辑将在一个单独的方法中:

public static void DoStuff()
{

// Image Path
   var path_image_1 = await SecureStorage.GetAsync("image_1");

   MultipartFormDataContent multiContent = new MultipartFormDataContent();
   multiContent.Headers.ContentType.MediaType = "multipart/form-data";

   // About 10 Fields like this
   multiContent.Add(new StringContent(Email), "email");

   // About 10 Images
   var image_1 = File.ReadAllBytes(path_image_1);
   multiContent.Add(new ByteArrayContent(image_1, 0, image_1.Count()), "images", path_image_1);


   HttpClient httpClient = new HttpClient();
   var response = await httpClient.PostAsync(url, multiContent);
   string serverResponse = await response.Content.ReadAsStringAsync();
}

Here 是一个基本示例,展示了它的实际应用。