簡體   English   中英

UPDATE: Azure DevOps API: Sending commands to the REST API that are JSON instead of a URI

[英]UPDATE: Azure DevOps API: Sending commands to the REST API that are JSON instead of a URI

I am a little new to using the REST API for Azure DevOps and have it working fine where I can send my requests that are basically the URIs I see on the website for the API. 然后我得到 JSON 響應並將其從 JSON 響應反序列化為 class 並停止運行。

下面是一個 function 示例,我使用它來通過其 ID 獲取工作項。 它使用來自網站的 URI。 我還可以通過將 URI 粘貼到瀏覽器中然后查看響應來進行測試。

我的問題是,如何使用命令更新工作項(例如添加鏈接),這不是我可以通過將其粘貼到瀏覽器中測試的 URI。 相反,它是一條 JSON 消息。

這是 API 網站,它顯示了添加工作項鏈接所需的 JSON 消息。
https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-a-link

這是他們用於更新工作項鏈接的 JSON 消息: [ { "op": "test", "path": "/rev", "value": 3 }, { "op": "add", "路徑”:“/relations/-”,“值”:{“rel”:“System.LinkTypes.Dependency-forward”,“url”:“https://dev.azure.com/fabrikam/_apis/wit/ workItems/300", "attributes": { "comment": "為依賴創建新鏈接" } } } ]

我是否需要其他function將其發送為Z0ECD11C1D7A287401D148A23BD7A23BD7A2F8Z,然后ZC1C1C425268E68ED111174F11174C174C174C174C174C174C174C174C174C.ABR? 我找不到 function 可能是什么樣子的示例。

任何有關如何發送 JSON 消息而不是 URI 以獲得響應的建議將不勝感激。

======================更新=====================

一個答案肯定幫助我最終實現了這一目標。 我粘貼了更新的 function 以防它幫助其他人。 我知道為此找到 VB.NET 樣本很棘手。 :)

謝謝!

更新代碼================================================= ==========

Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    SetUpHttpClient(client)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"
    Try
        If jsonMessageBody.Length > 0 Then
            

'################################################ ################### '### 對於所有具有 URI 和 JSON 消息的 PATCH 操作 ### '########## ################################################# ######### Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json") Dim method = New HttpMethod("PATCH") Dim request = New HttpRequestMessage(method, uri ) With {.Content = patchValue} Dim response = client.SendAsync(request).Result responseBody = response.Content.ReadAsStringAsync.Result() Else '################## #################################### '### 對於所有其他只有 URI 的操作### '############################################# ######### 使用響應作為 HttpResponseMessage = client.GetAsync(uri).Result statusCode = response.StatusCode.ToString() response.EnsureSuccessStatusCode() responseBody = response.Content.ReadAsStringAsync().Result End Using End If Catch End Try Dim answer As String() = {s tatusCode, responseBody} 返回答案結束 Function

Public Function GetTestCase(organization As String, project As String, TestCaseID As String) As WorkItemApi

    Dim dc As New DevCon.DevOpsConnector

    Dim response As String() = dc.GetRequest($"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{TestCaseID}?api-version=5.1&$expand=all")


    If response(0) <> "OK" Then
        Return Nothing
    End If

    Dim result As WorkItemApi = JsonConvert.DeserializeObject(Of WorkItemApi)(response(1))

    Return result

End Function


Public Async Function GetRequestAsync(ByVal getRequest As String) As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    SetUpHttpClient(client)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"

    Try

        Using response As HttpResponseMessage = client.GetAsync(getRequest).Result


            statusCode = response.StatusCode.ToString()
            ' Console.WriteLine("Response: " & statusCode)
            response.EnsureSuccessStatusCode()
            responseBody = response.Content.ReadAsStringAsync().Result
        End Using

    Catch
    End Try

    Dim answer As String() = {statusCode, responseBody}
    Return answer
End Function

您需要將字段數組序列化為 json 字符串。 使用 HttpClient class 檢查 C# 中的以下示例:

    public WorkItem CreateBugUsingHTTP()
    {
        string uri = _uri;
        string personalAccessToken = _personalAccessToken;
        string project = _project;
        string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));

        Object[] patchDocument = new Object[4];

        patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
        patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
        patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
        patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };

        using (var client = new HttpClient())
        {
            //set our headers
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

            //serialize the fields array into a json string
            var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");

            var method = new HttpMethod("POST");
            var request = new HttpRequestMessage(method, uri + "/" + project + "/_apis/wit/workitems/$Bug?api-version=5.1") { Content = patchValue };
            var response = client.SendAsync(request).Result;

            //if the response is successfull, set the result to the workitem object
            if (response.IsSuccessStatusCode)
            {
                var workItem = response.Content.ReadAsAsync<WorkItem>().Result;

                Console.WriteLine("Bug Successfully Created: Bug #{0}", workItem.Id);
                return workItem;
            }
            else
            {
                Console.WriteLine("Error creating bug: {0}", response.Content);
                return null;
            }
        }
    }

您可以從以下文檔開始:

https://docs.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1

Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
    Dim client As HttpClient = New HttpClient()
    client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
    client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", _accessTokenHttpClient)
    Dim statusCode As String = "NOTHING"
    Dim responseBody As String = "NOTHING"
    Try
        If jsonMessageBody.Length > 0 Then
            '#####################################################################
            '###  For all PATCH operations that have a URI and a JSON message  ###
            '#####################################################################
            Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
            Dim method = New HttpMethod("PATCH")
            Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
            Dim response = client.SendAsync(request).Result
            responseBody = response.Content.ReadAsStringAsync.Result()
        Else
            '#######################################################
            '###  For all other operations that have just a URI  ###
            '#######################################################
            Using response As HttpResponseMessage = client.GetAsync(uri).Result
                statusCode = response.StatusCode.ToString()
                response.EnsureSuccessStatusCode()
                responseBody = response.Content.ReadAsStringAsync().Result
            End Using
        End If
    Catch
    End Try
    Dim answer As String() = {statusCode, responseBody}
    Return answer
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM