[英]how to use request.AddParameter(restsharp) in 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.