尝试将图像附加到 Azure DevOps wiki 页面时出错

Error trying to attach an image to an Azure DevOps wiki page

我已成功使用 Azure DevOps API 通过独立的 C# 桌面应用程序创建多个 wiki 页面。现在我试图将图像(当前存储在本地)附加到 wiki(根据 https://docs.microsoft.com/en-us/rest/api/azure/devops/wiki/attachments/create?view=azure-devops-rest-6.0),但出现错误

The wiki attachment creation failed with message : The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

这是我用来读取图像文件并将其转换为 Base64 字符串的代码 - 正确吗?

string base64String = null; 
string img = File.ReadAllText(att.Value); 
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(img); 
base64String= Convert.ToBase64String(byteCredentials);

然后我为 API 调用创建“内容”

string data = @"{""content"": """ + base64String + @"""}";

和运行API调用

string url = "https://dev.azure.com/{organization}/{project}/_apis/wiki/wikis/{wikiIdentifier}/attachments?name=Image.png&api-version=6.0";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "PUT";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;

request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", "AzurePAT"))));

if (data != null)
{
     using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
     {
           writer.Write(data);
     }
}

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
     result = reader.ReadToEnd();
}

有人能看出这有什么问题吗?似乎没有记录使用编码的 Base64 字符串设置“内容”JSON 的概念,所以我做对了吗?

非常感谢任何帮助或建议,谢谢

图像文件不包含文本,它是二进制文件,调用File.ReadAllText可能会弄乱编码。尝试:

var img = File.ReadAllBytes(att.Value);
var base64String = Convert.ToBase64String(img);

此外,请求的正文只是一个字符串。您正在通过 JSON。您的代码应如下所示:

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(base64String);
}