【问题标题】:Can't access my repos in VSTS using REST API无法使用 REST API 在 VSTS 中访问我的存储库
【发布时间】:2017-10-13 07:16:54
【问题描述】:

我想访问托管在 VSTS 中的存储库以及相应存储库中的每个分支。下面是我的代码

 public class VSTSController : ApiController
{
    const String c_collectionUri = "https://****.visualstudio.com/DefaultCollection";
    const String c_projectName = "****";
    const String c_repoName = "****";

    [HttpGet]
    [Route("api/VSTS/Init")]
    public string Init()
    {

        // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
        VssCredentials creds = new VssClientCredentials();
        creds.Storage = new VssClientCredentialStorage();

        // Connect to VSTS
        VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);

        // Get a GitHttpClient to talk to the Git endpoints
        GitHttpClient gitClient = connection.GetClient<GitHttpClient>();

        // Get data about a specific repository
        var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;
        return repo.RemoteUrl;
    }
}

当我运行这段代码时,我得到一个异常Microsoft.VisualStudio.Services.Common.VssUnauthorizedException' occurred in mscorlib.dll but was not handled in user code。 如何对 VSTS REST API 进行身份验证?我无法理解关注这个documentation

【问题讨论】:

  • 对于网页应用,您需要使用 OAuth 或直接指定凭证(令牌或替代帐户)。 (正如丹尼尔所说)

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


【解决方案1】:

评论准确地告诉您为什么在 WebAPI 应用程序中实现此功能时遇到问题:// Interactively ask the user for credentials, caching them so the user isn't constantly prompted

它不能以交互方式提示输入凭据,所以它失败了。

身份验证documentation 提供了几个示例来演示不同的身份验证方法。最简单的可能是个人访问令牌:

VssConnection connection = new VssConnection(new Uri(collectionUri), new VssBasicCredential(string.Empty, pat));

其中pat 是一个包含有效个人身份验证令牌的变量。

但是,您可能希望最终实现 OAuth 身份验证,该身份验证已详细记录并提供了 sample code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多