-
Notifications
You must be signed in to change notification settings - Fork 91
WebApiProxy on the client side
This extension provides a proxy endpoint in your service (with /api/proxies
as the default) that serves a JavaScript client (using JQuery) and/or service metadata.
The following examples will assume a Person API on the server:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
}
public class PeopleController : ApiController
{
public Person[] Get() {
...
}
public Person Get(int id) {
...
}
}
Simply reference the proxy endpoint provided inside your HTML and you're good to go:
<script src="/api/proxies" type="text/javascript"></script>
It allows you to use it in JavaScript like this:
$.proxies.person.get()
.done(function(people) {
//do something with people
});
$.proxies.person.get(2) //get person with id = 2
.done(function(person) {
//do something with person
});
This functionality was adopted from ProxyApi - kudos to Stephen Greatrex :)
Generate a C# proxy on the client-side based on the metadata provided by a service implementing WebApiProxy.
Install this package from NuGet:
Install-Package WebApiProxy.CSharp
Note: This package requires the libraries of ASP.NET Web API Client (version 5.2 or higher)
Note: The automatic generation of code upon project build is now completely opt-in. You need to explicitly specify if you want the proxy to be generated on every build.
The C# proxy code will be generated every time you re-build the project (only if you explicitly specified generateOnBuild="true"
) and is based on specific configuration in the WebApiProxy.config
file:
<proxy endpoint="http://myservice.net/api/proxies" />
The endpoint
property is mandatory and provides the generator the URI of the metadata endpoint. See the WebApiProxy Configuration File page to read more on the config file.
Note: The generated code is cached to avoid compilation errors if the service isn't reachable at that time
You can also generate proxy code on demand by using the Nuget Package Manager Console. Simply run the commandlet:
WebApiProxy-Generate-CSharp
After the code generation it can be used like:
using (var client = new PeopleClient())
{
var response = await client.GetAsync(2); //get person with id = 2
var people = await response.Content.ReadAsAsync<Person[]>();
}
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.
It even has nice Intellisense including documentation provided by the documentation provider:
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