httpclient.post

Topics: Web Api
Jan 20, 2012 at 4:12 PM

Hi -

Sorry, this is probably a muppet of a question. I've written my first basic REST api and I want to access it from a WinForm. I've dug up this code from the help file;

static void AddContact(string name)
{
    HttpClient client = new HttpClient();

    Contact contact = new Contact() { Name = name };
    var response = client.Post("http://localhost:9000/api/contacts/",
        new ObjectContent<Contact>(
            contact, JsonMediaTypeFormatter.DefaultMediaType));

    Console.WriteLine("Status: {0}", (int)response.StatusCode);
}

However, I don't get the option to Post, just PostAsync. Can you explain where this has gone to? I'm stumped.

All the best,

Phil.
Jan 20, 2012 at 5:20 PM
Edited Jan 20, 2012 at 5:26 PM

Just do PostAsync.
Your thread will not continue, the method it uses is just async so it doesn't hold a thread.

client.PostAsync

Console.WriteLine(1) <-- will not execute until PostAsync is done 

Actually I think it might just wait when you ask for the response /shrug. Just know that it works.

Jan 23, 2012 at 12:06 PM

Hi -

Once I added .result at the end it forced the thread to wait.

All the best,

Phil.