Response.Redirect() in iFrame, redirect parent win

2019-03-20 16:32发布

问题:

I know this isn't possible, but what is the best alternative for wanting to do Response.Redirect from an iFrame, to redirect the parent page?

回答1:

You can not do this using ASP.NET. ASP.NET on server side can redirect incoming request and can't know about a parent frame.

But if you want to redirect parent frame on some server side condition you can call JavaScript from server like this:

protected void Page_Load(object sender, EventArgs e) {
   ClientScriptManager.RegisterClientScriptBlock(this.GetType(), 
       "RedirectScript", "window.parent.location = 'http://yoursite.com'", true);
}

And of course you can use simple JavaScript window.parent.location = 'http://yoursite.com' on client side.



回答2:

I just used the following code with success. It even bypassed the X-Frame-Options SAMEORIGIN and allows redirection from one domain to another one in an iframe:

string url = "https://siteurl.com";
Response.Write("<script>top.location='"+url+"';parent.location='"+url+"';</script>");

With string interpolation (since C# 6):

string url = "https://siteurl.com";
Response.Write($"<script>top.location='{url}';parent.location='{url}';</script>");


回答3:

Response.Clear();
Header.Controls.Add(new LiteralControl(@"
<script type=""text/javascript"">
top.location = ""/Logout.aspx"";
parent.location = ""/Logout.aspx"";
</script>
"));