Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proxy a REST API with .NET 4

Tags:

c#

.net

I'm trying to write a simple, pass-through proxy in .NET.

I have a REST api hosted at some external domain (http://exampleapi.com),

And I want to pass through all requests sent to my application (get, post, etc). JSONP isn't an option.

So if I ask for GET localhost:1234/api/pages => GET http://exampleapi.com/pages Likewise if I POST localhost:1234/api/pages => POST http://exampleapi.com/pages

The big problem I have, and what I can't seem to find elsewhere - is that I don't want to parse this JSON. Everything I've searched through seems to center around HttpClient, but I can't seem to figure out how to use it correctly.

Here's what I have so far:

public ContentResult Proxy()
{
    // Grab the path from /api/*
    var path = Request.RawUrl.ToString().Substring(4);
    var target = new UriBuilder("http", "exampleapi.com", 25001);
    var method = Request.HttpMethod;

    var client = new HttpClient();
    client.BaseAddress = target.Uri;

    // Needs to get filled with response.
    string content;

    HttpResponseMessage response;
    switch (method)
    {
        case "POST":
        case "PUT":
            StreamReader reader = new StreamReader(Request.InputStream);
            var jsonInput = reader.ReadToEnd();

            // Totally lost here.
            client.PostAsync(path, jsonInput);

            break;
        case "DELETE":
            client.DeleteAsync(path);
            break;
        case "GET":
        default:
            // need to capture client data
            client.GetAsync(path);
            break;
    }

    return Content(content, "application/json");
}
like image 842
Jon Jaques Avatar asked Nov 06 '12 23:11

Jon Jaques


1 Answers

You'll need to create a HTTP Server, receive the request, then your code will pull the information out of that request, and generate a new request to the new server, receive the response, and then send the response back to the original client.

Client -> C# Server -> Rest API server

Here's a sample HTTP Server that is open source. https://github.com/kayakhttp/kayak

like image 182
Walk Avatar answered Oct 26 '22 12:10

Walk