C# Can';t在RestSharp中设置多部分/相关ContentType
我需要使用多部分/相关ContentType。我喜欢这样:C# Can';t在RestSharp中设置多部分/相关ContentType,c#,restsharp,C#,Restsharp,我需要使用多部分/相关ContentType。我喜欢这样: RestRequest request = new RestRequest(); request.AddParameter("Content-Type", "multipart/related", ParameterType.HttpHeader); 但我总是会 多部分/表单数据 在Http请求中 有没有办法强制多部分/相关的?根据它们的: 如果您有文件,RestSharp将发送一个多部分/表单数据请求。 您的参数将作为表单中此请求的
RestRequest request = new RestRequest();
request.AddParameter("Content-Type", "multipart/related", ParameterType.HttpHeader);
但我总是会
多部分/表单数据
在Http请求中
有没有办法强制多部分/相关的?根据它们的:
如果您有文件,RestSharp将发送一个多部分/表单数据请求。
您的参数将作为表单中此请求的一部分
不要以为有办法解决这个问题。我为此苦恼了几天,一直在努力寻找解决办法。我的解决方案来自几天内的几个不同帖子,因此我为没有链接到它们而道歉。下面是一个示例函数,用于以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;
}
如果您按照以下步骤操作,则此功能在今天看来确实有效:
request.AddHeader("Content-Type", "multipart/related")
request.AddJsonBody(…);
request.AddFile(file.Name, file.FullName, "application/pdf");
它确实附加了边界并对其进行了适当的管理;但是,我仍在研究调整每个身体部位的头部的可行性,因为它似乎没有直接的支持。是的,这是我通过阅读Github上的源代码发现的。请检查此答案