我正在尝试使用以下代码创建工作项:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0");
httpWebRequest.ContentType = "application/json-patch+json";
httpWebRequest.Credentials = new NetworkCredential("me",Settings.Default.token);
httpWebRequest.Method = "PATCH";
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
op="add",
path= "/fields/System.Title",
value="New bug from application"
});
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
HttpWebResponse httpResponse = null;
try { httpResponse = (HttpWebResponse) httpWebRequest.GetResponse(); }
catch (WebException e)
{
//Exception catched there, error 404
Console.WriteLine(e.Status); //Writes ProtocolError
throw;
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
但是我收到错误404(未找到)。 当我改变方法(PUT或POST)时,我得到了一个可视工作室页面的代码。
当我要去https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0时,我可以看到一些json。所以这不是URL错误。
答案 0 :(得分:1)
我终于可以做我想做的事了:
public async Task CreateBug(Bug bug)
{
string token = Settings.Default.token;
string requestUrl = "https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0";
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = this.GetProxy(),
UseProxy = true,
UseDefaultCredentials = true
};
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "me", token))));
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUrl)
{
Content = new StringContent(GetStrJsonData(), Encoding.UTF8,
"application/json-patch+json")
};
HttpResponseMessage hrm = await httpClient.SendAsync(request);
Response = hrm.Content;
}
我使用的是HttpClient
而不是HttpWebRequest