c# -复制内容到流时出错



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

如果它有时有效,那么重试几次可能会有所帮助。如果您使用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();
}

下面是一个基本的例子。

最新更新