我需要使用multipart / related ContentType。我喜欢这个:
RestRequest request = new RestRequest();
request.AddParameter("Content-Type", "multipart/related", ParameterType.HttpHeader);
但我总是得到
的multipart / form-data的
在Http请求中
有没有办法强制多部分/相关?
答案 0 :(得分:0)
答案 1 :(得分:0)
我为此困扰了几天,一直在努力寻找解决方案。我的解决方案来自几天以来的几篇不同文章,因此我很抱歉没有链接到他们。下面是一个示例函数,该函数以json主体和base64 pdf字符串作为文件来执行多部分/相关的POST。
public static void PostBase64PdfHttpClient(string recordID, string docName, string pdfB64)
{
string url = $"baseURL";
HttpClient client = new HttpClient();
var myBoundary = "------------ThIs_Is_tHe_bouNdaRY_";
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"UN:PW"));
client.DefaultRequestHeaders.Add("Authorization", $"Basic {auth}");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{url}/api-endpoint");
request.Headers.Date = DateTime.UtcNow;
request.Headers.Add("Accept", "application/json; charset=utf-8");
MultipartContent mpContent = new MultipartContent("related", myBoundary);
mpContent.Headers.TryAddWithoutValidation("Content-Type", $"multipart/related; boundary={myBoundary}");
dynamic jObj = new Newtonsoft.Json.Linq.JObject(); jObj.ID = recordID; jObj.Name = docName;
var jsonSerializeSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var json = JsonConvert.SerializeObject(jObj, jsonSerializeSettings);
mpContent.Add(new StringContent(json, Encoding.UTF8, "application/json"));
mpContent.Add(new StringContent(pdfB64, Encoding.UTF8, "application/pdf"));
request.Content = mpContent;
HttpResponseMessage response = client.SendAsync(request).Result;
}
答案 2 :(得分:0)
如果您执行以下操作,看来今天可以使用:
request.AddHeader("Content-Type", "multipart/related")
request.AddJsonBody(…);
request.AddFile(file.Name, file.FullName, "application/pdf");
它确实附加了边界并进行了适当的管理;但是,我仍在研究调整每个身体部位的标头的可行性,因为似乎没有直接支持它。