0

I've just built my first ASP.NET Web API. I'm now trying to send an object to my API but not sure how to do it.

Here's my code so far:

Employee employee = new Employee();
employee.Id = 1234;
employee.FirstName = "John";
employee.LastName = "Smith";

using (var client = new HttpClient())
{
   client.BaseAddress = new Uri("http://myapi.mydomain.com");
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);

   **// How do I send my employee object to the API?**
   HttpResponseMessage response = await client.GetAsync("api/mycontroller/myaction");
   if (response.IsSuccessStatusCode)
   {
      var someObject = await response.Content.ReadAsAsync<myObjectType>();
   }
}
Sam
  • 19,814
  • 35
  • 141
  • 272
  • Why are you trying to send a whole `Employee` object in a GET request? – Ant P Oct 23 '14 at 18:30
  • It was just an example but there will be times when I'll have to send a lot of data e.g. registering a new user, new employee, etc. – Sam Oct 23 '14 at 18:39
  • Again, why would they be GET requests? – Ant P Oct 23 '14 at 18:39
  • It was just a quick example I put together and clearly didn't pay attention to POST vs GET. – Sam Oct 23 '14 at 18:43
  • Okay, but it makes a big difference to the answer of your question. Anyway, it sounds like this question isn't really anything to do with Web API at all and actually what you want is this: http://stackoverflow.com/questions/20005355/how-to-post-data-using-httpclient – Ant P Oct 23 '14 at 18:44
  • Or this: http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4 and then this: http://stackoverflow.com/questions/6117101/posting-jsonobject-with-httpclient-from-new-rest-api-preview-release-4 – Ant P Oct 23 '14 at 18:46

1 Answers1

0

What you need to do is perform a POST to the API endpoint and serialize your employee object as a json object, like so:

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

At the moment your existing code is simply performing a GET request.

HttpResponseMessage response = await client.GetAsync("api/mycontroller/myaction");

I would highly recommend you take a look at this article that clearly highlights how to call a Web API endpoint via C#.

I hope this helps.

Joseph Woodward
  • 8,837
  • 5
  • 39
  • 61