[英]What is the best way to code a redirect to SSL page in ASP.Net
I have been struggling with redirecting to SSL page code for a while for a ASP.Net Application. 对于ASP.Net应用程序,我一直在努力重定向到SSL页面代码。 I still have not found a good solution.
我仍然没有找到一个好的解决方案。 The problem is that I want to have the code be disabled if I am on localhost for example when I am debugging or coding but I can not get it to work.
问题是,如果我在本地主机上,例如在调试或编码时,我想禁用代码,但是我无法使它正常工作。 Another issue is that it has to redirect to another url so http://www.xx.com should redirect to https://Secure.xxx.com .
另一个问题是它必须重定向到另一个URL,因此http://www.xx.com应该重定向到https://Secure.xxx.com 。 Any ideas?
有任何想法吗?
If you want the ssl property to be set at the page level, you should create a custom attribute . 如果要在页面级别设置ssl属性,则应创建一个custom属性 。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class HttpsAttribute : Attribute{}
[HttpsAttribute]
public partial class PageSecured: YourCustomBasePage {}
Now the base page YourCustomBasePage
can check if this attribute
is set: 现在,基础页面
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());
}
}
}
To exclude your local machine from redirecting to HTTPS
, you can use a config value in your web.config
. 要排除本地计算机重定向到
HTTPS
,可以在web.config
使用config值。
private bool HTTPSEnabled{
get{ return ConfigurationManager.AppSettings["HTTPSEnabled"] == null || Boolean.Parse(ConfigurationManager.AppSettings["HTTPSEnabled"]); }
}
and you add the check to the first condition 然后将支票添加到第一个条件
if(!Request.IsSecureConnection && HTTPSEnabled)
I use this library in production. 我在生产中使用了这个库。 I prefer it to setting attributes because it is configuration driven, and configurable to a fine level.
我更喜欢它设置属性,因为它是配置驱动的,并且可以配置到很好的水平。 That being said, I'm not sure if it can redirect to a subdomain.
话虽这么说,我不确定它是否可以重定向到子域。 I'm not even sure why you would want that to happen.
我什至不知道您为什么要那样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.