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

问题描述 投票:0回答:2

我有这个表格,其中大约有 10 个字段,最多 10 个图像。我将它们上传到服务器,大多数时候它可以工作,但有时它会返回错误

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();
c# .net http xamarin
2个回答
2
投票

如果有时有效,那么重试几次可能会有所帮助。如果您使用 polly nuget 包,您可以将此代码包含在一个块中,该块将捕获异常并 重试 可配置的次数,并在它们之间设置可配置的等待时间。

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();
}

这里是一个基本示例,展示了它的实际效果。


0
投票

对我来说,这是因为我尝试从 Blazor 客户端发送到服务器的类太大了。主类有许多子元素的实例,每个子元素有多个相关的类。

一旦我清空了类引用,只留下类引用 ID,那么我就能够毫无问题地序列化并发送父类。

© www.soinside.com 2019 - 2024. All rights reserved.