开发者

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://w开发者_开发知识库ww.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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜