簡體   English   中英

HttpClient Post REST API 中的 C# 多部分表單數據

[英]C# Multipart form-data in HttpClient Post REST API

下面是來自 Postman 的代碼。 我需要在 POST 請求中發送這個正文和標題

var client = new RestClient("https://azr-stg.dev03.abs.ase.southcentralus.us.wc.net/files/v11");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/pdf");
request.AddHeader("X-Client-Id", "94437320-3bcf-498d-915a");
request.AddHeader("Tenant-Id", "0d3ad0cd-3bb3-4fc0-bd15");
request.AddHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA");
request.AddParameter("multipart/form-data; boundary=----WebKitFormBoundary7MA", "------WebKitFormBoundary7MA\r\nContent-Disposition: form-data; name=\"file\"; filename=\"sample.pdf\"\r\nContent-Type: application/pdf\r\n\r\n\r\n------WebKitFormBoundary7MA\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n\r\n------WebKitFormBoundary7MA--", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

上面的帖子在 Postman 中運行良好並且能夠上傳文件,但我想以編程方式執行此操作。 API 接受內容類型(如文本、pdf、圖像文件)。

如何使用多部分表單數據格式化正文和標題內容以使用 HttpClient 請求發送上述內容

這是我使用 HttpClient 的示例代碼的地方。 我收到錯誤的請求/內部服務器錯誤。

HttpClient _httpclient = new HttpClient()
using (var multiPartStream = new MultipartFormDataContent())
{



MemoryStream stream = new MemoryStream(filecontent);
//JsonSerializer.WriteObject(stream, newDocument);
ByteArrayContent firstPart = new ByteArrayContent(stream.ToArray());
firstPart.Headers.ContentType = JSON_GENERIC_MEDIA_TYPE;
firstPart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "metadata" };
multiPartStream.Add(firstPart);
stream.Dispose();


StreamContent otherContent = new StreamContent(content);
otherContent.Headers.ContentType = new MediaTypeHeaderValue(applicationContentType);
//otherContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file" };
otherContent.Headers.Add("Content-Disposition", $"form-data; name=\"file\"; filename=\"{docFullName}\"");

multiPartStream.Add(otherContent);


HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, urlTwo);
request.Content = multiPartStream;


 request.Headers.Accept.Add(“application/json”);
 request.Headers.Add("X-Client-Id", "94437320-3bcf-498d-915a");
 request.Headers.Add("Tenant-Id", "0d3ad0cd-3bb3-4fc0-bd15");
 HttpCompletionOption option = HttpCompletionOption.ResponseContentRead;

using (HttpResponseMessage response = _httpClient.SendAsync(request, option).Result)
{

if (response.IsSuccessStatusCode)
{
  var deserializedObject = JsonConvert.DeserializeObject<Walmart.MDM.MasterUIMVC.Helpers1.RootObject>(response.Content.ReadAsStringAsync().Result);
  return deserializedObject.properties.r_object_id.ToString();
}

感謝任何幫助。

所有,最后我能夠以編程方式在 C# 中重現 Postman 代碼。

我能夠在多部分表單數據中添加“元數據”屬性。

參考: 使用 HttpClient 上傳文件

string Seshat_URL = "https://azr-stg.dev03.abs.ase.southcentralus.us.wc.net/files/v11";
      using (var multiPartStream = new MultipartFormDataContent())
                {

                    multiPartStream.Add(new StringContent("{}"), "metadata");
                    multiPartStream.Add(new ByteArrayContent(filecontent, 0, filecontent.Length), "file", docName);
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Seshat_URL);
                    request.Content = multiPartStream;
                    //"application/json" - content type
                    request.Headers.Accept.Add(JSON_GENERIC_MEDIA_TYPE);  
                    request.Headers.Add("X-Client-Id", ClientId);                
                    request.Headers.Add("Tenant-Id", TenantId);

                    HttpCompletionOption option = HttpCompletionOption.ResponseContentRead;
                    System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

                    using (HttpResponseMessage response = _httpClient.SendAsync(request, option).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var deserializedObject = JsonConvert.DeserializeObject<Wc.MCM.UIMVC.Helpers1.BlobResponse>(response.Content.ReadAsStringAsync().Result);
                            return deserializedObject.fileId.ToString();
                        }                        
                    }

                }//End Try

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM