问题描述
我正在尝试使用API从azure devops服务器下载文件.API给出了成功响应,但是没有文件被下载。如果我们删除format参数,我们将获得文件链接的响应。通过单击该文件没有得到已下载。
示例代码
var personalaccesstoken = "ic2pqkzaeqv2dummyTokenDummypa";
client1.BaseAddress = new Uri("https://dev.azure.com/organisatioTest/ProjectABC");
client1.DefaultRequestHeaders.Accept.Clear();
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}","",personalaccesstoken))));
HttpResponseMessage response1 = client1.GetAsync("_apis/git/repositories/e9e2f082-6f6d-99999b0bcc737a/items?scopePath=/Vjjj/DB/Data/ABC.sql&download=true&$format=zip&api-version=5.1").Result;
解决方法
在C#中,该URL可以这样构造(假设变量是通过方法调用传递的):
var url = $" https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/items?path={path}&api-version=5.1";
使用正确格式的URL,然后我们可以使用WebRequest类来调用API。例如:
var request = (HttpWebRequest)WebRequest.Create(address);
request.UserAgent = "VSTS-Get";
request.Headers.Set(HttpRequestHeader.Authorization,GetAuthenticationHeaderValue(authentication).ToString());
request.ContentType = "application/json";
request.Method = httpMethod;
response = (HttpWebResponse)request.GetResponse();
使用HttpWebResponse对象,我们可以获得一个Stream对象,然后可以将其用于将API结果写到本地文件中。例如:
using (var responseStream = GetResponseStream(response))
{ var fileName = Path.Get Filename(fileToDownload ?? ""); using (var fileStream = File.Create(Path.Combine(destination,fileName))) { responseStream.CopyTo(fileStream); }
}
请参考此链接以获取更多详细信息:Get file API和sample blog
更新1
感谢sagar的分享,有关更多详细信息,请参阅Download a file from azure devops server writes wrong data to the file
我们应该尝试使用个人访问令牌(PAT)。为了使用PAT进行身份验证,我们必须使用“基本”授权而不是“承载者”。此外,我们还没有将PAT单独添加到Request标头中使用用户名和PAT的组合。请说用户名:PAT的base-64编码字符串。
示例代码:
var personalaccesstoken = "wwwwwwwwwwwwwwwwwwy47b7ugkz32bubi64bw7fqdyfpa";
var base64Creds = Convert.ToBase64String(Encoding.ASCII.GetBytes("SPabbbal@ABCTech.com:"+ personalaccesstoken));
request.Headers.Set(HttpRequestHeader.Authorization,"Basic " + base64Creds);