Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"transparent" server side proxy for requests to ASP.NET Web API

Have an ASP.NET Web API endpoint that generates JSON responses. But due to two factors can't be consumed directly from a browser.

  1. cross-domain issues
  2. need to provide session ticket for the API that is known only server side

So I need a lightweight server side proxy for client(browser) requests to extend the request with session key. Do not want to impose an overhead deserializing client JSON requests or Web API JSON responses in the proxy code. Would like to pass the payload "as is" and deserialize client requests only Web API side and the Web API responses only client (browser) side. That is the proxy takes json from the browser and passes it directly to Web API. It also passes the JSON response from the Web API to the browser directly without deserialization. Just a dummy proxy that does not know anything about the data it transfers. Please suggest is it feasible and what is the best way to implement it. The existing web application (the one that is used to generate the client pages) is implemented using ASP.NET MVC 4.

Thanks in advance.

like image 621
AGS Avatar asked Sep 11 '14 14:09

AGS


1 Answers

update for 2021:

You should probably be looking at https://microsoft.github.io/reverse-proxy/ if you have found your way here

old answer:

I wrote one for a previous version of WebApi. The code should be fairly easy to update for your purposes.

The basic idea is that you create a WebApi DelegatingHandler that passes the request on to an HttpClient:

    public class ForwardProxyMessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("X-Forwarded-For", request.GetClientIp());
            if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Trace) request.Content = null;
            request.RequestUri = new Uri(request.RequestUri.ToString().Replace(":3002", "")); //comes through with the port for the proxy, rewrite to port 80
            request.Headers.AcceptEncoding.Clear();
            var responseMessage = await new HttpClient().SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            responseMessage.Headers.TransferEncodingChunked = null; //throws an error on calls to WebApi results
            if (request.Method == HttpMethod.Head) responseMessage.Content = null;
            return responseMessage;
        }

    }
like image 183
mcintyre321 Avatar answered Nov 09 '22 09:11

mcintyre321