我最近一直在通过API在TeamCity中进行身份验证。我可以直接在浏览器中访问资源(http://usr:pw@teamcity:8111/httpAuth/app/rest/..。),但以编程方式执行此操作会返回401-Unauthorized。
WebRequest request = WebRequest.Create("http://user:pwd@teamcity:8111/httpAuth/app/rest/projects");
request.Method = WebRequestMethods.Http.Get;
try
{
request.Timeout = Timeout.Infinite;
WebResponse response = request.GetResponse(); //Returns 401:Unauthorized
我可以毫无问题地使用guestAuth(http://teamcity:8111/guestAuth/app/rest/projects),因此WebRequest本身应该没有任何问题。
有没有人有想法?
答案 0 :(得分:7)
尝试添加您的凭据,然后发出request.it将获得您所需的内容。
var username = "abc";
var password = "123";
var encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);