我一直在为 ASP.Net 应用程序重定向到 SSL 页面代码而苦苦挣扎。我还没有找到好的解决办法。问题是,如果我在本地主机上,例如当我正在调试或编码时,我希望禁用代码,但我无法让它工作。另一个问题是它必须重定向到另一个网址,所以 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
可以检查是否设置了此属性
:
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)
关于c# - 在 ASP.Net 中编写重定向到 SSL 页面的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7169543/