簡體   English   中英

ASP.Net重定向到安全

[英]ASP.Net Redirect to secure

我想將頁面重定向到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);
        }
    }

而不是使用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);
    }
}

如果你這樣做,它將改變的只是架構。 所以,如果絕對的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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM