How to put an ASP.NET Core application behind a reverse proxy painlessly
When you develop a web application knowing in advance that it will sit behind a load balancer, there are a few things to keep in mind. One example is running a site in a Docker cluster (Swarm, for instance).
What changes?
If your application tries to determine:
- the host name,
- the protocol:
httporhttps, - the client's IP address,
it will get something quite different from what it needs. The reason is that for every client request the load balancer essentially makes a similar request to a cluster node. That is exactly when the parameters we care about change.
How to fix it?
To avoid this, you need to configure the load balancer a bit more and write a little code.
The load balancer has to set these HTTP headers:
- Host
- X-Forwarded-Proto - the protocol
- X-Forwarded-For - the client's IP address
The application, in turn, has to handle the last two headers correctly. For ASP.NET Core you can use the following code:
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
const string XForwardedProto = "X-Forwarded-Proto";
if (context.Request.Headers.TryGetValue(XForwardedProto, out StringValues proto))
{
context.Request.Protocol = proto;
context.Request.Scheme = proto;
}
await next();
});
}
}
This code solves the first two problems globally. Besides, it doesn't require changing the code that determines the current host and protocol. As for the client's IP address, you can get it in a similar way.
Only registered users can leave a comment.
Sign in or register to leave a comment.