Reputation: 70184
I would like to proxy every requests to a web application, pass it to another web application and then return my other web applications response to the original sender.
It should be able to handle all http methods
and content-types
etc. I should also be able to edit the incoming request and add additional headers and content.
The background for doing this is the security architecture for a project that has one web server in a public DMZ and then another web server in the internal network that is allowed to talk to the database server.
Found a thread for ASP.NET core but preferably it should be done with .Net Framework and not be dependent on an external library.
Creating a proxy to another web api with Asp.net core
Upvotes: 2
Views: 6602
Reputation: 70184
Found a good answer for Web API that led me in the right direction.
https://stackoverflow.com/a/41680404/3850405
I started out by adding a new ASP.NET Web Application -> MVC -> No Authentication.
I then removed everything accept Global.asax
, packages.config
and Web.config
.
I then edited Global.asax
to use a DelegatingHandler
like this:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(CustomHttpProxy.Register);
}
}
public static class CustomHttpProxy
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Proxy",
routeTemplate: "{*path}",
handler: HttpClientFactory.CreatePipeline(
innerHandler: new HttpClientHandler(),
handlers: new DelegatingHandler[]
{
new ProxyHandler()
}
),
defaults: new { path = RouteParameter.Optional },
constraints: null
);
}
}
public class ProxyHandler : DelegatingHandler
{
private static HttpClient client = new HttpClient();
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var forwardUri = new UriBuilder(request.RequestUri.AbsoluteUri);
forwardUri.Host = "localhost";
forwardUri.Port = 62904;
request.RequestUri = forwardUri.Uri;
if (request.Method == HttpMethod.Get)
{
request.Content = null;
}
request.Headers.Add("X-Forwarded-Host", request.Headers.Host);
request.Headers.Host = "localhost:62904";
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return response;
}
}
After this I had to add the static content and then everything worked.
Upvotes: 3