HttpClient Post REST API 中的 C# 多部分表单数据

标签 c# rest asp.net-core advanced-rest-client

以下是 Postman 的代码。我需要在 POST 请求中发送这个 Body 和 Header

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、图像文件)。

如何格式化正文和 header 内容以使用多部分表单数据通过 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 代码。

我能够在多部分表单数据中添加“元数据”属性。

引用:Upload Files Using 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

关于HttpClient Post REST API 中的 C# 多部分表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888921/

相关文章:

c# - 仅在 asp.net 中的 Convert.ToDateTime() 中获取日期

c# - 直接向U盘写入字节

c# - 响应.Cookies : How to append with expiration?

python - 构建微服务事件总线和 REST api (python/flask)

c# - 服务堆栈性能

c# - 如何在 asp net core 中模拟 session 对象

c# - 当我选择添加 Controller 时,为什么下拉列表中缺少我的数据上下文类?

c# - 如何在 ASP.NET Core 中根据请求配置服务

c# - 在 .NET 中,如何识别 C++ DLL 是在 DEBUG 还是 RELEASE 版本中?

PHP Rest API readAll 返回空响应