Skip to content

Browser Specific Extensions of HttpClient

December 13, 2012

REST is having a great impact on service/API development because it offers a way to access a service without requiring any specific library by embracing HTTP and its features. ASP.NET Web API makes it very easy to quickly build RESTful HTTP services.

These HTTP services can be consumed by a variety of clients including browsers, devices, machine etc. With .NET framework 4.5, we can use HttpClient to consume/send/receive RESTful HTTP services (for .NET framework 4.0, HttpClient is available as part of the ASP.NET Web API download). The HttpClient class provides a bunch of helper methods (example DeleteAsync, PostAsync, GetStringAsync, etc.) to consume a HTTP service very easily. ASP.NET Web API added some more extension methods (for example PutAsJsonAsync, PutAsXmlAsync, etc.) into HttpClient to further simplify usage.

In addition, HttpClient is also an ideal choice for writing integration test for RESTful HTTP service. Since a browser is a main client of any RESTful API, it is also important to test the HTTP service on a variety of browsers, it is also important to test HTTP service on variety of browsers. RESTful service embraces HTTP headers and different browsers send different HTTP headers.

There is a NuGet package which can exactly do this. This NuGet package will add overloads with an additional browser parameter for almost all the helper methods of HttpClient class.

Create/open your test project and install ImranB.SystemNetHttp.HttpClientExtensions NuGet package. Then, add this using statement of your class.

using ImranB.SystemNetHttp;

Then, you can start using any HttpClient helper method which include the additional Browser parameter. For example,

var client = new HttpClient(myserver);
var task = client.GetAsync("http://domain/myapi", 
    Browser.Chrome);
task.Wait();
var response = task.Result;

Here is the definition of Browser,

public enum Browser
{
    Firefox = 0,
    Chrome = 1,
    IE10 = 2,
    IE9 = 3,
    IE8 = 4,
    IE7 = 5,
    IE6 = 6,
    Safari = 7,
    Opera = 8,
    Maxthon = 9
}

These extension methods will make it very easy to write browser specific integration test. It will also help HTTP service consumer to mimic the request sending behavior of a browser. This package source is available on github. So, you can grab the source and add some additional behavior on the top of these extensions.

Testing a REST API is an important aspect of service development and today, testing with a browser is crucial.

Please leave your comments on how you would like to use this HTTPClient Extension in your projects.

From → ASP.NET, C#

Leave a Comment

Leave a comment