【发布时间】:2011-11-02 10:17:57
【问题描述】:
我一直在为 ASP.Net 应用程序重定向到 SSL 页面代码而苦苦挣扎。我仍然没有找到一个好的解决方案。问题是,如果我在本地主机上,例如在调试或编码时,我希望禁用代码,但我无法让它工作。另一个问题是它必须重定向到另一个 url,所以 http://www.xx.com 应该重定向到 https://Secure.xxx.com。有什么想法吗?
【问题讨论】:
我一直在为 ASP.Net 应用程序重定向到 SSL 页面代码而苦苦挣扎。我仍然没有找到一个好的解决方案。问题是,如果我在本地主机上,例如在调试或编码时,我希望禁用代码,但我无法让它工作。另一个问题是它必须重定向到另一个 url,所以 http://www.xx.com 应该重定向到 https://Secure.xxx.com。有什么想法吗?
【问题讨论】:
如果您希望在页面级别设置 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)
【讨论】:
我在生产中使用this 库。我更喜欢它而不是设置属性,因为它是配置驱动的,并且可以配置到很好的水平。话虽如此,我不确定它是否可以重定向到子域。我什至不知道你为什么要这样。
【讨论】: