c# - 在 ASP.Net 中编写重定向到 SSL 页面的最佳方法是什么

标签 c# asp.net ssl redirect

我一直在为 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/

相关文章:

c# - 使用linq c#计算CSV文件中一列的平均值

c# - 类中的方括号

c# - Visual Studio 2008 中无法识别的标记前缀或设备筛选器

c# - 理论 : Implementing MSMQ using SSL to send message

ssl - 如何使用 lftp 连接到 ftps 文件服务器并将文件推送到他们的服务器

c# - console.readline 之前显示一些东西

c# - 当表的列数多于类时使用 Dapper

c# - Devexpress 或 Telerik Controls 比较

c# - 自定义类 ASP.Net 5 MVC 6 中的应用程序设置

nginx - 尝试使用 SSL 为多个域设置反向代理时遇到 "111:Unknown Error"