【发布时间】:2021-12-07 20:17:38
【问题描述】:
我正在以编程方式将文件上传到远程服务器。这些文件相当大,我想向我的用户展示一份进度报告,以便他们可以看到正在发生的事情。我能够使用 Postman 实现上传,这有助于将整个内容翻译成 RestSharp。 但 RestSharp 不提供任何类型的进度跟踪。我尝试使用 HttpClient 实现相同的功能,但它在某处出错,服务器只是抛出一个“400 - 错误请求”,而没有确切说明它的坏处(它的 API 文档也不适合胆小的人)。
所以,这里是 Postman / RestSharp 提供的和正在工作的:
var client = new RestClient("https://opencast/ingest/addMediaPackage");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic FooBarBaz=");
request.AddParameter("creator", file.Creator);
request.AddParameter("title", file.Title);
request.AddParameter("flavor", "presentation/source");
request.AddParameter("description", file.Description);
try
{
request.AddFile("BODY", path);
IRestResponse response = await client.ExecuteAsync(request);
_logger.LogInformation($"Response after file upload: {response.StatusCode}");
File.Delete(path);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception when uploading files: {Message}", ex.Message);
}
这是我尝试用 HttpClient 做的事情(没有 try-catch):
var request = new HttpRequestMessage(HttpMethod.Post, $"https://opencast/ingest/addMediaPackage");
request.Headers.Add("Authorization", "Basic FooBarBaz=");
using var form = new MultipartFormDataContent();
using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(path));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "BODY", Path.GetFileName(path));
form.Add(new StringContent(file.Creator), "creator");
form.Add(new StringContent(file.Title), "title");
form.Add(new StringContent("presentation/source"), "flavor");
form.Add(new StringContent(file.Description), "description");
request.Content = form;
var client = clientFactory.CreateClient(); //which is a IHttpClientFactory
var response = await client.SendAsync(request);
此代码将文件发送到服务器,在完成上传后,服务器会抛出 400。 目前看不出区别。我可以拦截请求以查看它们的不同之处,但也许这里有人可以立即看到问题?
更新:它变得更奇怪了。如果我只使用 clientFactory.PostAsync(form) 并通过 form.Add 添加 Auth 标头,那么我会得到 200(即成功),但服务器只会吞下文件。
【问题讨论】:
-
'newRequest' 只是问题中的错字吗?您正在其他地方使用“请求”。
-
是的,这是一个错字。修好了。
-
没关系,但我能看到的唯一区别是文件是最后使用 RestSharp 添加的,但首先是在您的代码中。
标签: c# dotnet-httpclient restsharp