Simple RealProxy implementation that dispatches method calls as HTTP requests to remote servers.
- Quickly create a client for a REST service;
- Can be used with anything that accepts and responds using JSON-formatted data;
- Manipulate headers sent along with requests, and inspect headers received in responses;
- Inspect other response information, like the HTTP status code, total time elapsed and content length;
Considering a remote URL like http://some-server/api/foo
, where the fragment foo
maps to a FooController
:
-
Create an interface with methods that describe the requests and parameters you want to execute:
public interface IFoo { public IEnumerable<Bar> GetAllBars(); public void AddBar(Bar bar); public Bar GetBar(int id); // ... }
-
Decorate the interface with
ResourceAttribute
, specifying the fragment that corresponds to the controller:[Resource("foo")] public interface IFoo {
-
Decorate the method call with
HttpMethodAttribute
describing the HTTP verb used in the request:// GET /foo [HttpMethod(HttpMethod.Get)] public IEnumerable<Bar> GetAllBars(); // POST /foo [HttpMethod(HttpMethod.Post)] public void Add(Bar bar);
-
For methods that should use parameter values as part of the URL, decorate them with
ResourceAttribute
specifying a fragment with format codes, and the list of parameters used in the query string:// GET /foo/1 [Resource("{0}", "id")] public Bar GetBar(int id);
-
To create the proxy instance and make a request, call Proxy.For, specifying the root url:
var configuration = new ProxyConfiguration("http://some-server/api"); var remote = Proxy.For<IFoo>(configuration); var allBars = remote.GetAllBars(); // GET http://some-server/api/foo/
-
Optionally, add request headers to the configuration object before you create the proxy instance:
configuration.RequestHeaders["Some-Header"] = "some value"; var remote = Proxy.For<IFoo>(configuration); // will always send Some-Header
-
Inspect response headers by obtaining a context when calling Proxy.For:
ProxyContext theContext; var remote = Proxy.For<IFoo>(configuration, out theContext); // make a request var responseHeaderValue = theContext.Requests.Last().ResponseHeaders["Some-Header"];
See src/SimpleProxy.Sample for usage examples.
Licensed under the The MIT License (MIT). In others words, you can use this library for developement any kind of software: open source, commercial, proprietary and alien.