繁体   English   中英

使用www前缀的ASP.NET HTTP到HTTPS重定向

[英]ASP.NET HTTP to HTTPS redirect with www prefix

我正在使用以下简单代码在我的帐单目标网页上将http重定向到https:

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName =HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);        
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

如果网址中还没有包含www,我还需要它来检查并添加www。 为此,我需要添加什么内容?

像这样:

if (!serverName.StartsWith("www."))
    serverName = "www." + serverName;

以下代码假定服务器名称不以“ www”开头。 那么补救措施是,在当前服务器名称之前加上“ www”。

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName = Request.ServerVariables["SERVER_NAME"];
    if (!serverName.ToLowerCaseInvariant().StartsWith("www.")) {
       serverName = string.Format("www.{0}", serverName);
    }
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

就个人而言,我不喜欢这种做事方法。 我通常创建一个名为SecureDomain类的设置,然后使用逻辑来验证当前的ServerName是否SecureDomain匹配。 这样的事情。

// Suppose the value of GlobalAppSettings.SecureDomain
// is something like www.securestore.com

if (!Request.IsSecureConnection)
{
    // send user to SSL 
    string serverName = Request.ServerVariables["SERVER_NAME"];
    if (string.Compare(serverName, GlobalAppSettings.SecureDomain, true) != 0) {
       serverName = GlobalAppSettings.SecureDomain;
    }
    string filePath = Request.FilePath;
    Response.Redirect("https://" + serverName + filePath);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM