John Smith John Smith - 1 year ago 104
ASP.NET (C#) Question

c# mvc reroute request to different server

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("");

//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
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?

Answer Source

I had to do this in C# code for a Silverlight solution once. It was not pretty.

What you're wanting is called reverse proxying and application request routing.

First, reverse proxy solutions... they're relatively simple.

Here's Scott Forsyth and Carlos Aguilar Mares guides for creating a reverse proxy using web.config under IIS. Here's a module some dude named Paul Johnston wrote if you don't like the normal solution. All of these focus on IIS.

Non-IIS reverse proxies are more common for load balancing. Typically they're Apache based or proprietary hardware. They vary from free to expensive as balls. Forgive the slang.

To maintain consistency for the client's perspective you may need more than just a reverse proxy configuration. So before you go down the pure reverse proxy route... there's some considerations.

The servers likely need to share Machine Keys to synchronize view state and other stuff, and share the Session Store too.

If that's not consistent enough, you may want to implement session stickiness through Application Request Routing (look for Server Affinity), such that a given session cookie (or IP address, or maybe have it generate a token cookie) maps the user to the same server on every request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download