【问题标题】:Translating RestSharp request to HttpClient request将 RestSharp 请求转换为 HttpClient 请求
【发布时间】: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


【解决方案1】:

好的,我找到了解决方案。我不确定 WTF 是我还是服务器背后的人,但是...

...您需要添加文件内容last

是的,参数的顺序对此很重要。

【讨论】:

  • 我猜 API 的开发人员正在流式传输请求,并且需要文件之前的元数据才能知道如何处理它。它实际上说顺序在文档中很重要:It is important to always set the flavor of the next media file before sending the media file itself.develop.opencast.org/docs.html?path=/ingest#addMediaPackage-6 不过很好找。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2018-04-16
  • 2021-02-06
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多