Friday, September 5, 2014

Call an API controller with HttpClient from the C# side!

Following up on this, I found this which explains not only how to call an ASP.NET MVC Web API controller from within a regular MVC controller in C#, but also how to account for scenarios in which the API controller barfs.

using (var client = new HttpClient())
{
   client.BaseAddress = new Uri("http://www.example.com/");
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new
         MediaTypeWithQualityHeaderValue("application/json"));
   var whatever = new { Foo = 13, Bar = 42 };
   var response = client.PostAsJsonAsync("api/something",
         JsonConvert.SerializeObject(whatever)).Result;
   if (response.IsSuccessStatusCode)
   {
      MyCustomType myCustomType =
            response.Content.ReadAsAsync<MyCustomType>().Result;
      DoSomethingInteresting(myCustomType);
   } else {
      throw new Exception("Ouch!");
   }
}

 
 

Note that just as there is a .PostAsJsonAsync there is also a .PutAsJsonAsync and a bunch of other verb specific methods hanging off of HttpClient. The whatever variable above is the thing we are handing in to our ApiController at the method signature.

 
 

Addendum 9/27/2018: System.Net.Http is the namespace that drives HttpClient above.

No comments:

Post a Comment