简体   繁体   中英

What is the best way to code a redirect to SSL page in ASP.Net

I have been struggling with redirecting to SSL page code for a while for a ASP.Net Application. I still have not found a good solution. The problem is that I want to have the code be disabled if I am on localhost for example when I am debugging or coding but I can not get it to work. Another issue is that it has to redirect to another url so http://www.xx.com should redirect to https://Secure.xxx.com . Any ideas?

If you want the ssl property to be set at the page level, you should create a custom attribute .

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
 public sealed class HttpsAttribute : Attribute{}

[HttpsAttribute]
public partial class PageSecured: YourCustomBasePage {}

Now the base page YourCustomBasePage can check if this attribute is set:

protected override void OnInit(EventArgs e){ 
   if(!Request.IsSecureConnection){
      HttpsAttribute secureAttribute = (HttpsAttribute)Attribute.GetCustomAttribute(GetType(), typeof(HttpsAttribute));
      if(secureAttribute != null){
         //Build your https://Secure.xxx.com url
         UriBuilder httpsUrl = new UriBuilder(Request.Url){Scheme = Uri.UriSchemeHttps, Port = 443};
         Response.Redirect(httpsUrl.Uri.ToString());
      }
   }
}

To exclude your local machine from redirecting to HTTPS , you can use a config value in your web.config .

private bool HTTPSEnabled{
  get{ return ConfigurationManager.AppSettings["HTTPSEnabled"] == null || Boolean.Parse(ConfigurationManager.AppSettings["HTTPSEnabled"]); }
}

and you add the check to the first condition

if(!Request.IsSecureConnection && HTTPSEnabled) 

I use this library in production. I prefer it to setting attributes because it is configuration driven, and configurable to a fine level. That being said, I'm not sure if it can redirect to a subdomain. I'm not even sure why you would want that to happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM