如何使用TFS REST API以指定用户的身份对工作项进行更改

时间:2018-09-18 16:02:39

标签: c# rest tfs

我需要类似Make Changes to a TFS Work Item as a specific user的东西,但要使用TFS REST API。

所以:

new WorkItemTrackingHttpClient(new Uri("http://server:8080/tfs"), new VssCredentials(...));

下一步是什么?

1 个答案:

答案 0 :(得分:1)

Rest API中不支持模拟用户,SOAP API中支持。

user voice here可以建议该功能,您可以对其进行投票以在将来的版本中实现该功能...

要使用REST API更新工作项,您可以尝试以下示例

public class TFSClient
{
    public WorkItemTrackingHttpClient WorkItem { get; set; }
    public TFSClient()
    {            
        VssCredentials vssCred = new VssCredentials(new WindowsCredential(true));
        WorkItem = new WorkItemTrackingHttpClient(new Uri(TFSServer.Url), vssCred);
    }
}
 public static object UpdateWorkItemByID(int id)
    {
        try
        {
            JsonPatchDocument patchDocument = new JsonPatchDocument
            {
                new JsonPatchOperation()
                {                       
                    Operation = Operation.Add,
                    Path = ItemField.History,
                    Value = "Teste"
                }
            };            
            return  new TFSClient().WorkItem.UpdateWorkItemAsync(patchDocument, id).Result;              

        }

        catch (Exception e)
        {
            throw e;
        }
    }

您还可以通过直接与特定用户调用REST API来更新工作项:

例如:

VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(new NetworkCredential("username", "password", "domain")));

或者使用PowerShell:

Param(
   [string]$baseurl = "http://server:8080/tfs/DefaultCollection",  
   [string]$workitemid = "39",
   [string]$user = "Domain\user",
   [string]$token = "password"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
write-host $WorkitemType

function CreateJsonBody
{

    $value = @"
[
  {
    "op": "test",
    "path": "/rev",
    "value": 7
  },
  {
    "op": "add",
    "path": "/fields/System.Title",
    "value": "test0909ddd"
  }

]

"@

 return $value
}

$json = CreateJsonBody

$uri = "$baseurl/_apis/wit/workitems/$($workitemid)?api-version=2.2" #_apis/wit/workitems/"+"$"+"bug?api-version=2.2"
Write-Host $uri
$result = Invoke-RestMethod -Uri $uri -Method Patch -Body $json -ContentType "application/json-patch+json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}