简体   繁体   English

Azure DevOps REST API in a Azure Function

[英]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.我正在尝试为 Azure DevOps 团队和存储库创建一个 POST 请求,并希望通过 API 方法创建一个新团队和一个新存储库。 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.我的团队创建得很好,但我不知道如何扩展代码以在同一个 HttpRequest 中创建存储库,以及如何让“正文”同时包含团队名称和存储库名称,因为它们两者都具有相同的“名称”参数。

I'm quiet new to C# and Azure functions and don't know how to properly implement this in my own project.我对 C# 和 Azure 函数很陌生,不知道如何在我自己的项目中正确实现它。 I would really appreciate it if someone could guide me into the right direction.如果有人能引导我走向正确的方向,我将不胜感激。

I am using Visual Studio with .NET Core 3.0.我正在使用带有 .NET Core 3.0 的 Visual Studio。

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.用于创建团队和 repo 的 API 不同。 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;
            }

        }
    }

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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