First, let's write a utility class that returns whether the request is SSL or not:
/// <summary>
/// Gets if the url is secure or not
/// </summary>
public static bool isSecureURL
{
get
{
// Check the request
if (HttpContext.Current.Request.IsSecureConnection ||
(HttpContext.Current.Request.ServerVariables["HTTPS"] != null &&
HttpContext.Current.Request.ServerVariables["HTTPS"].ToLower() == "on"))
return true;
if ((!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString())) &&
(HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString().EndsWith("443")))
return true;
// url is not secure:
return false;
}
}
Notice that I use 2 condition checks. The first might work for some users but for others who go through proxy with no forwarding information, I'm trying to see if proxy is forwarding HTTP_HOST ending with SSL port (I use 443).
And now, to implement use something like this:
if (//My Condition to see whether I should implement SSL or not)
{
if (!Utility.isSecureURL)
Response.Redirect(Request.Url.ToString().Replace("http://", "https://"));
}
Love coding!
3 comments:
Hi,
I tried this but i hv the following error as,
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Give me the Solution.
You can also try:
Request.IsSecureConnection
Or you can check if Request.Url.Scheme contains "https" or not.
Post a Comment