繁体   English   中英

将 RestSharp 请求转换为 HttpClient 请求

[英]Translating RestSharp request to HttpClient request

我正在以编程方式将文件上传到远程服务器。 这些文件相当大,我想向我的用户提供一份进度报告,以便他们可以看到正在发生的事情。 我能够使用 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(即 Success),但服务器只会吞下文件。

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

...您需要最后添加文件内容。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM