代码之家  ›  专栏  ›  技术社区  ›  tRuEsAtM

无法使用REST API访问VST中的我的repos

  •  2
  • tRuEsAtM  · 技术社区  · 7 年前

     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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Daniel Mann    7 年前

    该评论准确地告诉了您在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 提供。