问题解决了:还是微信在接受素材是对于multipart/form-data要求和HttpClient中的MultipartFormDataContent格式存在差异导致的,也就是boundary的值不可以存在双引号。完成代码如下:
public MaterialImageReturn UploadMaterialImage(MaterialImage imageFile, string token)
{
var apitype = "material";
var url = string.Concat(BaseUrl, apitype, "/add_material", "?access_token=", token, "&type=", "thumb");
var boundary = "fbce142e-4e8e-4bf3-826d-cc3cf506cccc";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter");
client.DefaultRequestHeaders.Remove("Expect");
client.DefaultRequestHeaders.Remove("Connection");
client.DefaultRequestHeaders.ExpectContinue = false;
client.DefaultRequestHeaders.ConnectionClose = true;
var content = new MultipartFormDataContent(boundary);
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
var contentByte = new ByteArrayContent(imageFile.ImageByte);
content.Add(contentByte);
contentByte.Headers.Remove("Content-Disposition");
contentByte.Headers.TryAddWithoutValidation("Content-Disposition", "form-data; name=\"media\";filename=\"111.png\"" + "");
contentByte.Headers.Remove("Content-Type");
contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png");
try
{
var result = client.PostAsync(url, content);
if (result.Result.StatusCode != HttpStatusCode.OK)
throw new Exception(result.Result.Content.ReadAsStringAsync().Result);
if (result.Result.Content.ReadAsStringAsync().Result.Contains("media_id"))
{
var resultContent = result.Result.Content.ReadAsStringAsync().Result;
var materialEntity = JsonConvert.DeserializeObject<MaterialImageReturn>(resultContent);
return materialEntity;
}
throw new Exception(result.Result.Content.ReadAsStringAsync().Result);
}
catch (Exception ex)
{
throw new Exception(ex.Message + ex.InnerException.Message);
}
}