我已经成功地使用了Azure DevOps API来创建多个wiki页面,通过一个独立的c#桌面应用程序。现在我试图将图像(当前存储在本地)附加到wiki(如https://learn.microsoft.com/en-us/rest/api/azure/devops/wiki/attachments/create?view=azure-devops-rest-6.0),但得到一个错误
wiki附件创建失败,提示:input is not a有效的Base-64字符串,因为它包含一个非Base-64字符两个填充字符,或填充中的非法字符字符。
这是我用来读取图像文件并将其转换为Base64字符串的代码-这是正确的吗?
string base64String = null;
string img = File.ReadAllText(att.Value);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(img);
base64String= Convert.ToBase64String(byteCredentials);
然后创建"content"作为
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);
}