Monday, April 27, 2009

WCF Rest Client

In my humble opinion the easiest way to create REST client in .NET is using "WCF REST Starter Kit Preview"

Step 1
Add references to:

  • Microsoft.Http.dll
  • Microsoft.Http.Extention.dll
These dlls could be found in installation directory of WCF REST Starter Kit (C:\Program Files (x86)\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies\... in my case)

Step 2

using Microsoft.Http;


Step 3
Create HTTP client

HttpClient http = new HttpClient(baseUrl);

You can also add authentication (basic)

http.TransportSettings.Credentials = new NetworkCredential(userName, password);


Step 4 (Get)
Get resource

// Optional. Add query parameters
HttpQueryString query = new HttpQueryString();
query.Add("f", "xml");
// Add relative uri of a resource
Uri uri = new Uri("resource_name", UriKind.Relative);
// Get Resource
HttpResponseMessage resp = http.Get(uri,query);


Step 4 (Post/Put/Delete/)
HttpClient has support of Post/Put/Delete methods

No comments:

Post a Comment