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

Azure DevOps REST API创建仓库POST请求实现求助(.NET Core+React)

Step-by-Step Guide to Creating an Azure DevOps Repo via REST API (.NET Core + React)

Hey there! I totally get how overwhelming REST APIs can feel when you're just starting out. Let's walk through exactly what you need to do to create an Azure DevOps repository using the POST API, building on the code you already have.

First: Fix Your Existing Async Method

Before we jump into the POST request, let's tweak your GetRepositories method to use async Task instead of async void. Async void is only intended for event handlers, and using it here can lead to unhandled exceptions:

public static async Task GetRepositories() {
    try {
        var personalaccesstoken = "PAT_FROM_WEBSITE";
        using (HttpClient client = new HttpClient()) {
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", "", personalaccesstoken))));
            using (HttpResponseMessage response = await client.GetAsync(
                "https://dev.azure.com/{your-organization}/_apis/git/repositories?api-version=5.1")) {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
    }
}

Key Concepts for the POST Request to Create a Repo

To create a repository, you need three main things:

  1. The correct API endpoint: Unlike the GET request, creating a repo requires specifying the target project. The endpoint is:
    https://dev.azure.com/{your-organization}/{your-project}/_apis/git/repositories?api-version=5.1
    
  2. A request body: This is where you specify the new repo's name (required) and optional details like description. The body needs to be JSON formatted.
  3. Proper authentication: Same as your GET request—using your PAT with Basic auth.

Implementing the Create Repository Method

Let's add a new async method to your AzureDevOps class that handles the POST request. We'll use a simple class to define the request body (this makes serialization easier), but you could also use an anonymous object if you prefer.

Step 1: Define the Request Body Class

Add this class somewhere in your project (it can be inside the AzureDevOps class or as a separate file):

public class CreateRepoRequest
{
    public string Name { get; set; }
    public string Description { get; set; } // Optional
}

Step 2: Add the CreateRepository Method

public static async Task<string> CreateRepository(string organizationName, string projectName, string repoName, string pat)
{
    try
    {
        var requestBody = new CreateRepoRequest
        {
            Name = repoName,
            Description = "Created via .NET Core REST API" // Optional, adjust as needed
        };

        // Serialize the request body to JSON
        string jsonBody = System.Text.Json.JsonSerializer.Serialize(requestBody);

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", pat))));

            // Create the StringContent with the JSON body
            var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json");

            // Send the POST request
            using (HttpResponseMessage response = await client.PostAsync(
                $"https://dev.azure.com/{organizationName}/{projectName}/_apis/git/repositories?api-version=5.1", content))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody; // Returns the created repo's details as JSON
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error creating repository: {ex.ToString()}");
        throw; // Re-throw if you want the caller to handle the exception
    }
}

How to Use This Method

You can call this method from your .NET Core backend like this:

// Replace these with your actual values
string orgName = "YourOrganization";
string projectName = "YourProject";
string newRepoName = "MyNewRepo";
string pat = "YourPAT";

string repoDetails = await AzureDevOps.CreateRepository(orgName, projectName, newRepoName, pat);
Console.WriteLine(repoDetails);

Working with React.js

Since you're planning to use React with .NET Core, here's a quick note on integration:

  • Never expose your PAT in React code: Frontend code is visible to users, so storing your PAT there is a huge security risk.
  • Create a .NET Core API endpoint: Build a controller in your .NET Core app that calls the CreateRepository method, then have your React app send a request to your own backend endpoint.
  • Example React fetch call (to your .NET Core API):
    const createRepo = async (repoName) => {
      try {
        const response = await fetch('/api/azuredevops/createrepo', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ repoName: repoName }),
        });
        const data = await response.json();
        console.log('Repo created:', data);
      } catch (error) {
        console.error('Error creating repo:', error);
      }
    };
    

Important Things to Check

  • PAT Permissions: Make sure your PAT has the Code (Write) permission enabled. You can adjust this when creating the PAT in Azure DevOps.
  • Replace Placeholders: Don't forget to swap out {your-organization}, {your-project}, and YourPAT with your actual values.
  • Test with Postman First: If you're still having issues, test the POST request directly in Postman to confirm the API works before adding it to your code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:02:52