I have a web application which is a mesh of a few different servers and 1 server is the front-end server which handles all request external incoming requests.

So some of these request will have to be passed along to different servers and ideally the only thing I want to change is the host and Uri fields of these request. Is there a way to map an entire incoming request to a new outgoing request and just change a few fields?

I tried something like this:

// some controller
public HttpResponseMessage get()
{
    return this.Request.Rewrite("192.168.10.13/api/action");
}


//extension method Rewrite
public static HttpResponseMessage Rewrite(this HttpRequestMessage requestIn, string Uri) {
    HttpClient httpClient = new HttpClient(new HttpClientHandler());
    HttpRequestMessage requestOut = new HttpRequestMessage(requestIn.Method, Uri);
    requestOut.Content = requestIn.Content;

    var headerCollection = requestIn.Headers.ToDictionary(x => x.Key, y => y.Value);
    foreach (var i in headerCollection)
    {
        requestOut.Headers.Add(i.Key, i.Value);
    }

    return httpClient.SendAsync(requestOut).Result;
}

The issue I am having is that this has a whole slew of issues. If the request is a get Content shouldn't be set. THe headers are incorrect since it also copies things like host which shouldn't be touched afterwards etc.

Is there an easier way to do something like this?

Related posts

Recent Viewed