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

调用Azure DevOps API创建首个提交及主分支时遇MethodNotAllowed错误

调用Azure DevOps API创建首个提交和main分支时遭遇MethodNotAllowed错误

我在C#中调用服务器上的Azure DevOps(ADO)API,尝试创建首个提交和main分支,但收到MethodNotAllowed错误返回码。我的PAT拥有完全权限,且推送操作理应使用POST方法。追踪代码时看到请求端点为:

https://*********/_apis/git/repositories/******-****-****-****-************/pushes?api-version=7.1-preview.1

(注:上述混淆处理的仓库ID是有效的,已用于其他正常请求)

相关代码如下:

public async Task<bool> CreateFirstCommitAndMainBranchAsync(string repositoryName, string readmeContent)
{
    string endpoint = $"https://{m_adoSspServer}/_apis/git/repositories/{repositoryInfos.Id}/pushes?api-version=7.1-preview.1";

    var commitData = new
    {
        commits = new[]
        {
            new
            {
                comment = "Initial commit with README.md",
                changes = new[]
                {
                    new
                    {
                        changeType = "Add",
                        item = new
                        {
                            path = "/README.md"
                        },
                        newContent = new
                        {
                            content = readmeContent,
                            contentType = "rawText"
                        }
                    }
                }
            }
        },
        refUpdates = new[]
        {
            new
            {
                name = "refs/heads/main", // 创建main分支
                oldObjectId = "0000000000000000000000000000000000000000" // 不确定这里该填什么
            }
        }
    };

    string jsonContent = JsonConvert.SerializeObject(commitData);

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}")));

        var response = await client.PostAsync(endpoint, new StringContent(jsonContent, Encoding.UTF8, "application/json"));

        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"Failed to create commit and branch: {response.StatusCode} - {response.ReasonPhrase}"); // MethodNotAllowed
            return false;
        }
    }

    return true;
}

内容的提问来源于stack exchange,提问作者pf12345678910

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:24:51