【问题标题】:Retrieve Pull Request from Work Item in Azure Devops WebApi从 Azure Devops WebApi 中的工作项中检索拉取请求
【发布时间】:2020-09-27 16:10:53
【问题描述】:

我想使用 Azure DevOps WebAPI 以编程方式检索与 Azure DevOps 中的工作项关联的所有拉取请求的信息。 我已经想出了如何检索

的实例
Microsoft.TeamFoundation.WorkItemTracking.WebApi.Model.WorkItem

对于我的工作项目。

要查找与其相关的拉取请求,我可以遍历关系字段并找到 Url 包含 PullRequestId 的关系。在该字符串的末尾,我可以找到与GetPullRequestAsync 一起使用的拉取请求 ID。

网址可能如下所示:

vstfs:///Git/PullRequestId/2139bb34-57e3-4d7d-a6e1-1c0542a45e29%2F8a2b707f-ca7a-418d-8462-2bf076a54aad%2F39723

所以我的代码应该是这样的:

foreach ( WorkItemRelation wir in wi.Relations)
{
     if ( wir.Url.Contains("PullRequestId"))
     {
          var pr = build.GetPullRequestAsync("<MyProject>", "Providername", "39723", "repository id").Result;
          // Do somethin with pr object
     }
}

我的问题如下

  1. 解析 URL 以检索拉取请求 ID 似乎不是一个好方法。我不能从某个字段中获取 id 吗?
  2. GetPullRequestAsync 需要提供者名称和存储库 ID。 但是如果该信息不能从实例中检索到 Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemRelation
  3. 还有其他更简单的方法来做我想做的事情吗?

【问题讨论】:

    标签: azure-devops azure-pipelines azure-devops-rest-api


    【解决方案1】:

    我建议您使用属性,而不是依赖PullRequestId。在 URL 中你会找到所有你需要的:

    var credential = new VssBasicCredential(string.Empty, "PAT");
    var connection = new VssConnection(new Uri("https://dev.azure.com/thecodemanual/"), credential);
    var witClient = connection.GetClient<WorkItemTrackingHttpClient>();
    
    var build = connection.GetClient<BuildHttpClient>();
    
    var repoClient = connection.GetClient<GitHttpClient>();
    
    var workItem = witClient.GetWorkItemAsync(1, expand: Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models.WorkItemExpand.Relations).Result;
    
    foreach (var relation in workItem.Relations)
    {
        if((string)relation.Attributes["name"] == "Pull Request")
        {
            Console.WriteLine(relation.Url);
    
            var segment = relation.Url.Split("/").Last();
    
            var ids = segment.Split("%2F");
    
            var repo = repoClient.GetRepositoryAsync(ids[1]).Result;
    
            Console.WriteLine(repo.Name);
    
            var pr = build.GetPullRequestAsync(ids[0], "TfsGit", ids[2], ids[1]).Result;
    
            Console.WriteLine(pr.Title);
            // Do somethin with pr object
        }
    
    }
    

    【讨论】:

    • 非常感谢。这正是我所需要的。是否可以在给定 id 的情况下检索存储库的名称?以及为什么在 WebAPI 上找到文档如此困难。代码示例在网上不容易找到
    • 是的。有可能的。我将此添加到上面编写的代码中。
    【解决方案2】:

    据我所知,没有其他更好的方法可以实现这一目标。目前已知的方法是从 url 中获取 pull request id。

    您可以从响应中检索与"name": "Pull Request" 的关系。然后你可以用%2F分割url字符串,拉取请求id是最后一部分。

    关于第二个问题,你可以使用这个Get Pull Request By Idrest api 来获取拉取请求的详细信息。只需在请求中提供拉取请求 ID。

    GET https://dev.azure.com/{organization}/{project}/_apis/git/pullrequests/{pullRequestId}?api-version=5.1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2020-07-13
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多