Derik Whittaker

Syndication

News


Consuming WebApi endpoints in your application

In my prior post I walked you though how to setup WebApi in a self hosted environment.  In this post we will take a look at how to consume a WebApi endpoint. We will do this by using the code from the prior example as well as by creating a new console application.

Before we get started you are going to want to create our console application and add references to the following assemblies.

  • System.Json
  • System.Net.Http
  • System.Net.Http.Formatting

Step 1: Creating our HttpClient

When connecting to any remote endpoint there are many ways to do this, in our post we are going to use the HttpClient which is part of the System.Net.Http namespace.

var httpClient = new HttpClient();

Step 2: Connecting to our endpoint and consuming our data

Once we have our  httpClient created we need to do something useful with it.  The code below is what is needed in order to do exactly this.

httpClient.GetAsync( "http://localhost:8080/endpoints/episode/" )
    .ContinueWith( result =>
                        {
                            var response = result.Result;

                            response.EnsureSuccessStatusCode();

                            response.Content
                                .ReadAsAsync<JsonArray>()
                                .ContinueWith( readResult =>
                                                    {
                                                        var array = readResult.Result;

                                                        foreach ( var element in array )
                                                        {
                                                            Console.WriteLine(element);
                                                        }

                                                    } );

                        } );

The code above is a bit much so lets take a few to break it down and take a closer look at its parts

  1. The first thing we are doing is using the HttpClient to connect to the our endpoint.  As you can see we are doing this Async via the Task Parallel library.
  2. Next you should see that once we get a response from the remote endpoint we are going to handle the results via the .Result property.  We will also want to ensure that the connection as valid so we should call response.EnsureSuccesStatusCode.  If any status but success (200) is returned an exception will be thrown.
  3. Once we know we have a good connection we need to read in the content.  we will read the content via the ReasAsAsync method and provide it the type of JsonArray, this tells the code how to format/deserialize the result content stream.  of course you could read this as a raw stream or string but that is no fun.
  4. Once we have our formatted content we can do something useful with it.  Of course in this example I am not converting my content into an object, I am leaving it as raw Json, but if need an object you can use the JsonSerializer to get an object.

As you can see consuming a WebApi is pretty straight forward and does involve a ton of coding or effort.

Till next time,


Posted 02-28-2012 8:35 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

Kelly Brownsberger wrote re: Consuming WebApi endpoints in your application
on 02-29-2012 8:26 AM

Thanks for the post Derik

I'm guessing you meant to say "As you can see consuming a WebApi is pretty straight forward and does NOT involve a ton of coding or effort" there at the end.

Derik Whittaker wrote WebApi and Json Deserialization into an object model
on 03-01-2012 5:23 PM

If you use WebApi with the Asp.Net MVC framework you may not realize that there is some ‘magic’ that

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)