何时应该在 ASP.NET 页面生命周期中对安全页面强制实现 SSL?
我的意思是我应该在page_load 中执行它吗?或者OnInit?或者其他一些功能?
我正在使用以下代码对某些页面强制实现 SSL,但我应该将该代码放在哪里?早些时候,我将其放置在 OnInit 函数中,但这对于 ASP.NET 向导来说效果不佳。 需要先检查是否回发吗?
如果回发丢弃 https,我的代码不应该强制执行它吗?如果回发不删除 https,我的代码是否应该停止重定向并移至向导的下一步?看起来它一直在重定向。
if (!HttpContext.Current.Request.IsSecureConnection) {
HttpContext.Current.Response.Redirect(SiteNavigation.ResolveAbsoluteUrl(true, HttpContext.Current.Request.Url.PathAndQuery));
}
最佳答案
你基本上有两个选择。
如果您希望所有经过身份验证的页面都在 SSL 下运行,您可以在表单例份验证上设置 requireSSL="true"属性。只需确保您的登录页面也在 HTTPS 上运行。
您还可以逐页进行设置。我发现这在继承自 System.Web.UI.Page 的“页面基”类中效果很好,并且所有页面都继承自(而不是 System.Web.UI.Page)。
public class PageBase : System.Web.UI.Page
{
public bool RequiresSSL {get; set;}
string currentPage = Request.Url.ToString();
public PageBase()
{
Init += new EventHandler(PageBase_Init);
}
void PageBase_Init(object sender, EventArgs e)
{
if ((RequiresSSL) && (WebConfigurationManager.AppSettings["SSLavailable"] == "true"))
{
if (currentPage.ToLower().StartsWith("http://"))
{
redirectTo = "https://" + currentPage.Substring(7);
Response.Redirect(redirectTo);
}
}
else
{
if (currentPage.ToLower().StartsWith("https://"))
{
redirectTo = "http://" + currentPage.Substring(8);
Response.Redirect(redirectTo);
}
}
}
}
当您在没有 SSL 的测试模式下运行时,SSLavailable 的 AppSettings 值允许您关闭整个机制。
对于需要在SSL模式下运行的页面,只需设置RequiresSSL即可:
public partial class ChangePassword : PageBase
{
public ChangePassword()
{
PreInit += new EventHandler(ChangePassword_PreInit);
}
void ChangePassword_PreInit(object sender, EventArgs e)
{
RequiresSSL = true;
}
}
它工作得非常顺利,他们在安全页面之后访问的任何其他页面都会自动切换回 HTTP 协议(protocol)。
关于ASP.NET SSL - 问题是回发,因此 OnInit 等将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1766443/