简体   繁体   中英

Azure DevOps REST API in a Azure Function

I'm trying to create a POST Request for Azure DevOps Teams and Repositories and want to create a new team and a new repository through the API method. My Team is created fine but I don't know how to extend the code to create a repository in the same HttpRequest and also how do I have the 'body' to include both the name of the team and the name of the repository as they both have the same 'name' parameter.

I'm quiet new to C# and Azure functions and don't know how to properly implement this in my own project. I would really appreciate it if someone could guide me into the right direction.

I am using Visual Studio with .NET Core 3.0.

Here is the code so far:

using System.IO;
using System;
using System.Net;
using Microsoft.Azure.WebJobs;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs.Extensions.Http;


namespace TeamsAdd
{
    public static class TeamsAdd
    {
        [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] 
             HttpRequestMessage req)
        {
            var personalaccesstoken = "";
            var body = new
            {
                name = "myteamname",
                
                project = new
                {
                    id = "xxxxxxx",
                    projectname = "myprojectname",
                }
        };

            using (HttpClient client = new HttpClient())
            {

                client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(
                        ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", "", personalaccesstoken))));

                //Connecting to the DevOps REST API
                var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://dev.azure.com/{organization}/_apis/projects/{projectId}/teams?api-version=6.0");
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");

                //Reading Server Response
                using (HttpResponseMessage response = await client.SendAsync(requestMessage))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                    }

                    return req.CreateResponse(HttpStatusCode.Created, "Teams created successfully!");
                }
            }
        }
    }
}


The API used to create a team and repo are different. For more details, please refer to here and here . So we cannot create the two resources in one request. we need to send two requests to create the two different resources.

For example

public static class Function2
    {
        public static HttpClient Client = new HttpClient();
        public static string PAT = "";
        [FunctionName("Function2")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
             
            Object teamBody = new
            {
                name = "mytest7878orf",

            };

           Object repoBody = new
            {
                name = "mytest85698",
                project= new {
                    id = "8d5fa9a0-1061-4891-977b-f91189a0dcbe",
                }
            };


           var teamRes=  sendRequest(HttpMethod.Post, "https://dev.azure.com/{organization}/_apis/projects/{projectId}/teams?api-version=6.0", teamBody);
           var repoRes=  sendRequest(HttpMethod.Post, "https://dev.azure.com/{organization}/{projectId}/_apis/git/repositories?api-version=6.0", repoBody);

            var res = new
            {
                 teamRes = JsonConvert.DeserializeObject(teamRes),
                repoRes = JsonConvert.DeserializeObject(repoRes)

            };

            return req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(res), "application/json");
        }

        public static string sendRequest(HttpMethod method, string url, Object body = null) {
            Client.DefaultRequestHeaders.Accept.Add(
                 new MediaTypeWithQualityHeaderValue("application/json"));

            Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(
                    ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", "", PAT))));

            //Connecting to the DevOps REST API
            var requestMessage = new HttpRequestMessage(method, url);
            if (body != null) {
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
            }

            using (HttpResponseMessage response =  Client.SendAsync(requestMessage).Result)
            {
                if (!response.IsSuccessStatusCode)
                {
                    try
                    {
                        response.EnsureSuccessStatusCode();
                    }
                    catch (HttpRequestException ex) {

                        return ex.Message;
                    }


                }
               var content =  response.Content.ReadAsStringAsync().Result;
              
                return content;
            }

        }
    }

在此处输入图像描述

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM