尝试使用Test Suite
创建TFS 2017 REST API
时,我收到错误消息:
System.Net.Http.HttpRequestException - 响应状态代码没有 表示成功:500(内部服务器错误)
我试过的代码:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string base64StringPat = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Configs.Pat)));
AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", base64StringPat);
client.DefaultRequestHeaders.Authorization = authHeader;
string url = "http://vmctp-tl-mtm:8080/tfs/DefaultCollection/SgkProject/_apis/test/Plans/7/Suites/8?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module1\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
我使用Microsoft的此文档来调用API:Create a test suite
请指导我解决问题。
答案 0 :(得分:-1)
HTTP代码500表示这是您服务器上的错误。尝试处理此POST请求时,服务器引发了异常。
因此,此错误与HttpClient
无关。只需检查您的服务器,看看导致异常的原因。
可能是服务器不期望指定的content type
。 POST StringContent
会将内容类型设置为text/plain
。您可能会发现服务器并不喜欢这样。在这种情况下,只需尝试找出服务器期望的媒体类型,并设置Headers.ContentType
实例的StringContent
。
无论如何,我可以通过以下示例创建套件,您可以尝试一下:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CreateTestSuite
{
class Program
{
public static void Main()
{
Task t = CreateTestSuite();
Task.WaitAll(new Task[] { t });
}
private static async Task CreateTestSuite()
{
try
{
var username = "username";
var password = "password";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
string url = "http://server:8080/tfs/DefaultCollection/LCScrum/_apis/test/plans/212/suites/408?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module3\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}