0

我想将页面重定向到 ASPX 文件的安全连接。

要求客户复制并粘贴如下所示的 URLfoo.com.au到浏览器中。

我在下面有这段代码处理文件背后的代码,但我想知道它何时部署到生产环境中是否会更新 URL,www因为https://www提供给客户端的 URL 中没有www

protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        if (!Request.IsLocal && !Request.IsSecureConnection)
        {
            string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
            Response.Redirect(redirectUrl);
        }
    }
4

2 回答 2

2

与其使用 Request.Url,不如使用Request.Url.AbsoluteUri。此外,您不应假设 URL 将以小写形式输入。我会将代码修改为:

if (!Request.IsLocal && !Request.IsSecureConnection)
{
    if (Request.Url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
    {
        string sNonSchemeUrl = Request.Url.AbsoluteUri.Substring(Uri.UriSchemeHttp.Length);
        // Ensure www. is prepended if it is missing
        if (!sNonSchemeUrl.StartsWith("www", StringComparison.InvariantCultureIgnoreCase)) {
            sNonSchemeUrl = "www." + sNonSchemeUrl;
        }
        string redirectUrl = Uri.UriSchemeHttps + sNonSchemeUrl;
        Response.Redirect(redirectUrl);
    }
}

如果您这样做,它将改变的只是架构。所以,如果 absoluteUri 是

http://foo.com.au

它将更改为

https://foo.com.au

最后一点:当我们这样做时,我们从未在 OnPreInit 中尝试过,我们总是在 Page_Load 中执行此逻辑。我不确定在页面生命周期的那部分重定向会产生什么后果(如果有的话),但是如果遇到问题,可以将其移至 Page_Load。

于 2013-07-04T02:03:36.677 回答
0

这是我的最终实现,以说明请求通过https://foo而不是https://www.foo

        if (!Request.IsLocal &&
            !Request.Url.AbsoluteUri.StartsWith("https://www.", StringComparison.OrdinalIgnoreCase))
        {
            string translatedUrl;
            string nonSchemeUrl = Request.Url.AbsoluteUri;
            string stringToReplace = (Request.Url.Scheme == Uri.UriSchemeHttp ? Uri.UriSchemeHttp + "://" : Uri.UriSchemeHttps + "://");
            nonSchemeUrl = nonSchemeUrl.Replace(stringToReplace, string.Empty);
            if (!nonSchemeUrl.StartsWith("www", StringComparison.InvariantCultureIgnoreCase))nonSchemeUrl = "www." + nonSchemeUrl;
            translatedUrl = Uri.UriSchemeHttps + "://" + nonSchemeUrl;
            Response.Redirect(nonSchemeUrl);
        }
于 2013-07-04T22:53:47.240 回答