【发布时间】:2021-11-02 17:39:23
【问题描述】:
我有一个旧的基于 asp.net webform 的网站,我想将流量从 HTTP 重定向到 HTTPS
我正在使用下面的代码
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://example.com") || HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://www.example.com"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
Response.RedirectPermanent("https://www.example.com/en/", false);
}
上面的代码应该适用于所有基于 HTTP 的 url,但它只能在 url 下方正确重定向
重定向适用于以下
- http://example.com 被重定向到 https://www.example.com/en/
- http://www.example.com 被重定向到 https://www.example.com/en/
但如果我有更长的网址,如下所示,它不会重定向
- http://example.com/en/news/news-title1
- http://example.com/en/news/news-title2
- http://example.com/en/blog/blog-titlex
我不确定我是否在代码中做错了什么?当我使用.Contains() 时,它应该将所有基于 HTTP 的 url 重定向到 HTTPS
更新:我意识到我必须使用HttpContext.Current.Request.Url.AbsoluteUri 来获取完整的 URL 路径。
即使更改了代码 if 块也没有被执行,我注意到两件事
-
HttpContext.Current.Request.Url.AbsoluteUri的输出返回 Secure,但在浏览器上它总是显示不安全,如屏幕截图所示 - 其次,当我在 Incognito 上运行同一页面或在 Chrome 或 FF 上作为 Private 运行时,它会从显示页面重定向为安全但不执行 if 语句。
所以在这两种情况下,事情都是令人困惑的
if (HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower().Contains("http://example.com") || HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower().Contains("http://www.example.com"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
Response.RedirectPermanent("https://www.example.com/en/", false);
}
test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
【问题讨论】:
-
您是否尝试调试以查看这些 URL 是否实际命中了此代码?你把这段代码放在哪里了?