在ASP.Net中将重定向编码到SSL页面的最佳方法是什么

时间:2011-08-24 01:41:10

标签: c# asp.net ssl redirect

我一直在努力为ASP.Net应用程序重定向到SSL页面代码一段时间。我还没有找到一个好的解决方案。问题是,如果我在localhost上,我希望禁用代码,例如我在调试或编码时,但我无法使其工作。另一个问题是它必须重定向到另一个网址,因此http://www.xx.com应该重定向到https://Secure.xxx.com。有什么想法吗?

2 个答案:

答案 0 :(得分:5)

如果您希望在页面级别设置ssl属性,则应创建custom attribute

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

[HttpsAttribute]
public partial class PageSecured: YourCustomBasePage {}

现在,基页YourCustomBasePage可以检查是否设置了attribute

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());
      }
   }
}

要将本地计算机排除在重定向至HTTPS之外,您可以在web.config中使用配置值。

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

并将检查添加到第一个条件

if(!Request.IsSecureConnection && HTTPSEnabled) 

答案 1 :(得分:1)

我在制作中使用this库。我更喜欢它设置属性,因为它是配置驱动的,并且可配置为精细级别。话虽这么说,我不确定它是否可以重定向到子域。我甚至不确定你为什么要这样做。