2
votes

I'm trying to create a work item with this code :

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);
}

But I get an error 404 (Not Found). When i change the method(to PUT or POST) I get a code for a visual studio page.

When i'm going to https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0 i can see some json. So this is not an URL error.

1

1 Answers

1
votes

I finally can do what I want :

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;
}

I've used an HttpClient instead of an HttpWebRequest