1
votes

Currently the same website is running under two different server configurations and under two different URLs.

  • A farm of IIS servers sitting behind a load balancer
  • A single IIS server with an elastic IP

For convenience it would be nice to have the same code running on all servers as it will simplify deployment procedures.

I know that I can do things like this:

if (string.Equals(HttpContext.Current.Request.Headers["X-Forwarded-Proto"], "https"))

This checks if the load balancer forwarded 'https' data. However, what I want to do is simply detect if a load balancer exists or not.

Essential I want to write: if(LoadBalancerExists) { do this stuff }

Does anyone know how to do this?

1
Add a rule on the load balancer to add a custom http header? And then read it. - abatishchev
How do I add a custom http header? - nu everest
Any reason you can't simply make this a configuration setting and set it in your deployment script? - Ian Mercer
Currently a deployment script is non-existent as I'm just testing at the moment, maybe that is the better way. - nu everest
At startup, retrieve the instance ID of the current EC2 instance, then make an API call to describe the ELB and then see if your instance ID is registered with the ELB. - jarmod

1 Answers

1
votes

It turns out that if the load balancer does not exist Request.Headers["X-Forwarded-Proto"] == null.

If it does exist Request.Headers["X-Forwarded-Proto"] == 'http' or 'https'

Quick Solution: if(Request.Headers["X-Forwarded-Proto"] == null) { do stuff }

Updated Solution with added security since headers can be spoofed:

ClientIP = Request.UserHostAddress;
Subnet = <enter your aws CIDR subnet address>;    // e.g. 172.0.0.0
Mask = <enter your aws VPC address>;              // e.g. 255.255.0.0

// Verify header
if(Request.Headers["X-Forwarded-Proto"] == null) {
    // Verify that ClientIP i.e. the LoadBalancer's IP is inside of our subnet.
    if(IsAddressOnSubnet(ClientAddress, Subnet, Mask)) {
        // do some stuff
    }
}

protected bool IsAddressOnSubnet(IPAddress Address, IPAddress Subnet, IPAddress Mask)
{
    try
    {
        Byte[] addressOctets = Address.GetAddressBytes();
        Byte[] subnetOctets = Mask.GetAddressBytes();
        Byte[] networkOctets = Subnet.GetAddressBytes();

        return
            ((networkOctets[0] & subnetOctets[0]) == (addressOctets[0] & subnetOctets[0])) &&
            ((networkOctets[1] & subnetOctets[1]) == (addressOctets[1] & subnetOctets[1])) &&
            ((networkOctets[2] & subnetOctets[2]) == (addressOctets[2] & subnetOctets[2])) &&
            ((networkOctets[3] & subnetOctets[3]) == (addressOctets[3] & subnetOctets[3]));
    }
    catch (System.Exception ex)
    {
        return false;
    }
}

Thanks to Michael-sqlbot for pointing out the security issue.

This aws reference is useful.

Reference for detecting that ip address is on subnet here thanks to Спасибо! Прекрасное решение!.