Detecting HTTPS in your asp.net c# web app is fairly straight forward in a normal environment with a single server solution, as you can see from the below example:
if (HttpContext.Current.Request.IsSecureConnection) { Response.Write("Using HTTPS"); } else { Response.Write("Using HTTP"); }
The problem comes when your web application is on multiple servers and behind a load balancer that doesn’t forward SSL. In these circumstances the certificate is installed on the load balancer and the traffic between it and the servers is HTTP, but if the ‘HTTP_X_FORWARDED_PROTO’ header is included (most load balancers have the option for include it) then you can use the below example:
bool isSecureConnectionDirect = HttpContext.Current.Request.IsSecureConnection; bool isSecureConnectionLoadBalanced = String.Equals(Request.ServerVariables["HTTP_X_FORWARDED_PROTO"], "https", StringComparison.OrdinalIgnoreCase); if(isSecureConnectionDirect || isSecureConnectionLoadBalanced) { Response.Write("Using HTTPS"); } else { Response.Write("Using HTTP"); }
To break it down, the below is used to check if HTTPS is used on a direct server browsing:
HttpContext.Current.Request.IsSecureConnection
The below is used to see if the ‘HTTP_X_FORWARDED_PROTO’ header is present:
String.Equals(Request.ServerVariables["HTTP_X_FORWARDED_PROTO"], "https", StringComparison.OrdinalIgnoreCase)
If you check for both and one is present, then treat the connection as using HTTPS.