http redirection issue

2019-06-09 17:05发布

As far as I know, we can use two method to redirects http response.

  1. Using Java script window.location;
  2. Using HttpContext.Current.Response.Redirect in ASP.Net

From function and end user perspective, are the two methods interchangeable?

2条回答
Deceive 欺骗
2楼-- · 2019-06-09 17:31

window.location requires both javascript and for the browser to download and render the original page's contents (including css/scripts) first before the page is changed.

Response.Redirect, on the other hand, issues a 302 status code with a Location header. This causes the browser to instantly request the next page without downloading/rendering the original first.

Based on your other question, it's worth noting that window.location has the benefit of being able to execute other javascript before the location is changed. For example, changing the location of another frame AND the current frame at the same time.

查看更多
家丑人穷心不美
3楼-- · 2019-06-09 17:31

I'm not familiar with HttpContext.Current.Response.Redirect, but I guess it issues an HTTP 301 response or something similar.

HTTP response codes are ALWAYS preferred, because they are built-in to, well, HTTP. Everybody understands them and they always work. Search engines and other automated apps respect them as well.

The Javascript method on the other hand does not always work and is non-standard.

Furthermore, with HTTP codes the transferred data is kept to a minimum, while the Javascript method always needs to load a whole page.

EDIT: To illustrate:

This is all that needs to be transferred for an HTTP redirect to work, the standard HTTP header:

HTTP/1.1 301 Moved Permanently
Location: http://somenewlocation.com/

For Javascript, it's more like this:

HTTP/1.1 200 OK
Date: Wed, 22 Jul 2009 07:56:14 GMT
Server: Apache/2.0.63 (Unix) mod_ssl/2.0.63 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Transfer-Encoding: chunked
Content-Type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script>window.location = "somewhere.com"</script>
</head>
<body>
</body>
</html>

A complete HTML document needs to be transferred and evaluated, which will take a lot longer and is not understood by anything but Javascript-savvy browsers.

查看更多
登录 后发表回答