Skip to content

WebApi C# Proxy Generator

Pharylon edited this page Jan 22, 2015 · 13 revisions

Generate a C# proxy on the client-side based on the metadata provided by a service implementing WebApiProxy.

Install via NuGet

Install this package from NuGet:

Install-Package WebApiProxy.CSharp

Note: This package requires the libraries of ASP.NET Web API Client (version 5 or higher)

Usage

The C# proxy code will be generated every time you re-build the project and is based on specific configuration in the WebApiProxy.config file:

<?xml version="1.0" encoding="utf-8" ?>
<proxy name="MyWebApiProxy" 
       clientSuffix="Client" 
       endpoint="http://myservice.net/api/proxies" 
       namespace="WebApi.Proxies" />

Note: If the compiled code does not appear after a build, you might find the .cs file in the $SolutionFolder\obj\Debug folder (assuming you are building in Debug mode).

The name and endpoint properties are mandatory and provides the generator the name of the proxy and the URI of the metadata endpoint. The clientSuffix and namespace properties are optional and allows you to customize the code generation by specifying a suffix for the client (default is "Client" and namespace for the the code (default is "WebApi.Proxies").

Note: The generated code is cached to avoid compilation errors if the service isn't reachable at that time

Given a PeopleController on the service-side:

public class PeopleController : ApiController
{
        /// <summary>
        /// Gets all people with a given the name
        /// </summary>
        /// <param name="name">The criteria to search for</param>
        /// <returns>People collection</returns>
        public Person[] Get(string name)
        {
            return new Person[]{
                new Person { Id = 3, FirstName = "sss", LastName = "sqqqq"},
                new Person { Id = 3, FirstName = "sss", LastName = "sqqqq"}
            };
        }
}

can be used like this on the client-side:

using (var client = new PeopleClient())
{
    var response = await client.GetAsync("Fanie");

    var people = await response.Content.ReadAsAsync<Person[]>();
}

Code snippet

Use the webapiproxy code snippet to quickly create the code structure above. Just type "webapiproxy" followed by the TAB key.

Note: If the types are not found (or resolved) after build, simply give your project a restart or restart Visual Studio.

Great developer experience with Intellisense

It even has nice Intellisense including documentation provided by the documentation provider: Intellisense

Note: The documentation on the Intellisense will only appear if the service uses the documentation provider. You can use the ASP.NET Web API Help Page package on NuGet