什么是在ASP.Net中将重定向到SSL页面的最佳方法?
什么是在ASP.Net中将重定向到SSL页面的最佳方法?
我已经为ASP.Net应用程序苦苦挣扎了一段时间,以重定向到SSL页面代码。我仍然没有找到一个好的解决方案。问题是,我希望如果我在本地主机上,例如在调试或编码时,该代码被禁用,但我无法使其工作。另一个问题是,它必须重定向到另一个网址,因此http://www.xx.com应该重定向到https://Secure.xxx.com。有什么想法吗?
admin 更改状态以发布 2023年5月21日
如果您想要在页面级别设置ssl属性,则应创建一个自定义属性。
[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)