[英]How to Convert form inputs to json array and send it as http post request in body, using c# in mvc5
[英]C# - Send a file in the body of an http request using RestRequest
我嘗試在 POST http 請求的正文中發送 xlsx 文件(來自路徑)。 我能夠發送文件,但它作為損壞的文件到達。(我無法嘗試檢查 api 上的問題,因為它是 api 等亞馬遜等)這是我試過的代碼:
public async Task<string> PostPostman()
{
try
{
string filePath = @"D:\example2.xlsx";
FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);
streamContent.Headers.Add("Content-Type", "application/xlsx");
var client = new RestClient("https://api.xxx.com/v1/FileUpload");
var request = new RestRequest(Method.Post.ToString());
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/xlsx");
request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
request.AddParameter("application/xlsx", streamContent.ReadAsStringAsync().Result, ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return ex.Message;
}
}
我發現問題是ReadAsStringAsync()
打開了文件但沒有關閉它。
我找到的解決方案是使用File.ReadAllBytes(filePath)
發送文件,該文件讀取文件並將其關閉。
這是最終代碼:
public async Task<string> PostPostman()//found the code from the postman request I sent
{
try
{
string filePath = @"D:\example2.xlsx";
var client = new RestClient("https://api.xxx.com/v1/FileUpload");
var request = new RestRequest(Method.Post.ToString());
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/xlsx");
request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
request.AddParameter("application/xlsx", File.ReadAllBytes(filePath), ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return ex.Message;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.