【问题标题】:What is the best way to code a redirect to SSL page in ASP.Net在 ASP.Net 中编写重定向到 SSL 页面的最佳方法是什么
【发布时间】:2011-11-02 10:17:57
【问题描述】:

我一直在为 ASP.Net 应用程序重定向到 SSL 页面代码而苦苦挣扎。我仍然没有找到一个好的解决方案。问题是,如果我在本地主机上,例如在调试或编码时,我希望禁用代码,但我无法让它工作。另一个问题是它必须重定向到另一个 url,所以 http://www.xx.com 应该重定向到 https://Secure.xxx.com。有什么想法吗?

【问题讨论】:

标签: c# asp.net ssl redirect


【解决方案1】:

如果您希望在页面级别设置 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) 

【讨论】:

    【解决方案2】:

    我在生产中使用this 库。我更喜欢它而不是设置属性,因为它是配置驱动的,并且可以配置到很好的水平。话虽如此,我不确定它是否可以重定向到子域。我什至不知道你为什么要这样。

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 1970-01-01
      • 2018-12-21
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多