【问题标题】:C# - Error while copying content to a streamC# - 将内容复制到流时出错
【发布时间】:2021-07-29 11:31:09
【问题描述】:

我有这个表格,其中有大约 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();

【问题讨论】:

  • 上述设置存在许多潜在错误,无法从Error while copying content to a stream 推断出任何错误。网络连接可能有问题,另一端的侦听过程可能有问题,但侦听过程存储图像可能有问题,列表继续。
  • 谢谢,你能分享一些资源吗?我的代码也正确吗?
  • 您能否提供有关您的环境的更多信息?它的托管地点和方式等将有助于诊断潜在问题。

标签: c# .net http xamarin


【解决方案1】:

如果它有时有效,那么重试几次可能会有所帮助。如果您使用 polly nuget package,您可以将此代码包含在一个块中,该块将捕获异常和 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 是一个展示它的基本示例。

【讨论】:

  • 我安装了 polly nuget 包并粘贴了您的代码,但是现在当我单击提交按钮时,它什么也没做。实际上,有一个提交按钮,当点击代码被执行(发送表单数据到服务器)。添加Policy.Handle&lt;HttpRequestException&gt;().Retry(3, onRetry: (exception, retryCount) =&gt;{ }后,不经过大括号。
  • 我很抱歉。我有一段时间没有使用波莉了。我已经更新了我的答案。重试中的代码块正是您希望在每次重试之前发生的事情。你仍然需要在别处定义你的逻辑,然后执行策略来启动。另外,我建议阅读文档。这是一个非常基本的示例,Polly 库中有更多功能和选项。
  • 感谢现在完美运行.. 另外,只需进行小编辑,从 var policy.Execute(() =&gt; DoStuff()); 中删除 var,因为上面已经分配了 policy。再次感谢您的帮助:)
  • 我很乐意提供帮助!感谢您的反馈。我更新了代码示例。
猜你喜欢
  • 1970-01-01
  • 2016-01-18
  • 2020-04-10
  • 2018-02-15
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多