You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Azure DevOps REST API获取提交列表遇重定向及请求停滞问题

问题描述

尝试通过Azure DevOps REST API获取代码提交列表时,程序在获取repoResponse阶段一直处于等待状态。在浏览器中粘贴从Visual Studio获取的repoUri时,未触发基础身份验证密码提示,反而被重定向到登录页面。

所用C#代码

public async Task ListCommits()
{
    var pat = ConfigurationManager.AppSettings["PAT"];
    var encodedPat = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}"));

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedPat);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var repoUri = $"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repository}?api-version=6.0";
        var repoResponse = await client.GetAsync(repoUri);
        if (!repoResponse.IsSuccessStatusCode)
        {
            Console.WriteLine($"Failed to retrieve repository. Status code: {repoResponse.StatusCode}");
            return;
        }

        string repoResponseContent = await repoResponse.Content.ReadAsStringAsync();
        var repo = JObject.Parse(repoResponseContent);
        var repoId = repo["id"].ToString();

        var commitsUri = $"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repoId}/commits?searchCriteria.itemVersion.version=master&api-version=6.0";
        var commitsResponse = await client.GetAsync(commitsUri);
        if (!commitsResponse.IsSuccessStatusCode)
        {
            Console.WriteLine($"Failed to retrieve commits. Status code: {commitsResponse.StatusCode}");
            return;
        }

        string commitsContent = await commitsResponse.Content.ReadAsStringAsync();
        Console.WriteLine("Commits Response:");
        Console.WriteLine(commitsContent);

        var commitsData = Newtonsoft.Json.Linq.JObject.Parse(commitsContent);
        foreach (var commit in commitsData["value"])
        {
            var commitId = commit["commitId"].ToString();
            var changesUri = $"https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repoId}/commits/{commitId}/changes?api-version=6.0";
            var changesResponse = await client.GetAsync(changesUri);
            if (changesResponse.IsSuccessStatusCode)
            {
                string changesContent = await changesResponse.Content.ReadAsStringAsync();
                Console.WriteLine($"Changes for Commit ID {commitId}:");
                Console.WriteLine(changesContent);
            }
            else
            {
                Console.WriteLine($"Failed to retrieve changes for commit {commitId}. Status code: {changesResponse.StatusCode}");
            }
        }
    }
}

测试用curl命令

curl -u :theencodepath= https://dev.azure.com/Organization/Project/_apis/git/repositories/TheRepo?api-version=6.0

curl返回结果

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="https://spsprodeus21.vssps.visualstudio.com/_signin?realm=de

原因分析与解决方案

核心问题:身份验证失败引发重定向阻塞

从curl返回的重定向结果可以看出,请求未通过Azure DevOps的身份验证,服务器返回3xx重定向响应。而HttpClient默认会自动跟随重定向,但登录页需要手动交互,无法自动完成验证,导致请求一直挂起。

具体修复步骤

  1. 修正PAT配置与权限

    • 检查PAT有效性:确保ConfigurationManager.AppSettings["PAT"]读取到的令牌无多余空格、换行符,且在Azure DevOps令牌管理页面中处于有效期内。
    • 验证PAT权限:必须勾选Code (Read)权限,且有效范围覆盖目标项目。
    • 修正curl命令:正确格式为curl -u :{你的PAT} https://dev.azure.com/Organization/Project/_apis/git/repositories/TheRepo?api-version=6.0,无需提前编码PAT,curl会自动处理。
  2. 禁用HttpClient自动重定向
    关闭自动跟随重定向,直接获取身份验证失败的状态码(401 Unauthorized),便于排查:

    using (var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }))
    {
        // 原有业务逻辑保持不变
    }
    
  3. 校验仓库与项目路径
    确认repoUri中的{organization}、{project}、{repository}拼写完全正确(区分大小写),repository可以是仓库名称或ID。

  4. 尝试更新API版本
    可切换至最新稳定版API(如api-version=7.1-preview.1),避免版本兼容问题。

额外排查方法

  • 使用浏览器隐私窗口访问repoUri,登出所有Azure DevOps账号后,会弹出基础认证提示,输入空用户名和PAT作为密码,测试是否能正常获取JSON数据。

内容的提问来源于stack exchange,提问作者Anders Lindén

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:17:12