我想将页面重定向到ASPX文件的安全连接。
要求客户端将类似此foo.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);
}
}
答案 0 :(得分:2)
使用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);
}
}
如果你这样做,它将改变的只是架构。所以,如果absoluteUri是
http://foo.com.au
它将被更改为
https://foo.com.au
最后一点:当我们完成此操作时,我们从未在OnPreInit中尝试过,我们总是在Page_Load中执行此逻辑。我不确定在页面生命周期的那一部分会有什么影响重定向,但如果遇到问题,可以将其移到Page_Load。
答案 1 :(得分: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);
}