ASP.Net重定向到安全

本文关键字:安全 重定向 Net ASP | 更新日期: 2023-09-27 18:20:52

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

客户端被要求将一个看起来像foo.com.au的URL复制并粘贴到浏览器中。

我有下面的代码在处理代码隐藏文件,但我想知道当它被部署到生产中时,这是否会更新URL,使其在https://www之后有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);
        }
    }

ASP.Net重定向到安全

与其使用Request.Url.AbsoluteUri,不如使用Request.Url。此外,您不应假设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);
    }
}

如果你这样做,它将改变的只是模式。所以,如果绝对Uri是

http://foo.com.au

它将改为

https://foo.com.au

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

这是我最后一次实现,目的是解释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);
        }