Al.
Al.

Reputation: 875

Using Response.Write and Response.Redirect at the same time

Below is Asp.net mvc code,

        public void Index()
        {
            Response.Write("Hey");
            Response.Redirect("https://www.google.com");
        }

 OR

 public void Index()
        {
            Response.Redirect("https://www.google.com");
            Response.Write("Hey");
        }

Here, Redirecting is working but not the Write(). Why Redirect is being given a preference? I mean why 302 and why not 200 in http response.

Note: This is not for addressing any real time scenario. Just have curiosity to know the reason or underlying behavior.

Upvotes: 1

Views: 5200

Answers (3)

Captain Kenpachi
Captain Kenpachi

Reputation: 7215

If you HAD some real-world scenario where you needed to do something like this, you could do the Response.Write in your code-behind/Controller (depending on if you're using WebForms or MVC) and add the redirect header in the body of your HTML page:

Controller:

public void Index()
{
    Response.Write("Hey");
}    

HTML:

<%
//response would show here
%>
<head>
    <meta http-equiv="refresh" content="10; url=https://www.google.com" />
</head>

Upvotes: 0

Black Cloud
Black Cloud

Reputation: 481

Here not given preference to Redirect , you are calling both Responce.Write and Responce.Redirect in same function then after write page directly redirect to your given url.

Upvotes: 0

jlvaquero
jlvaquero

Reputation: 8785

Respose.Write is working but when you execute Redirect the server sends a response with the headers:

HTTP/1.1 302 Object moved

Server: Microsoft-IIS/5.0

Location: somewhere/newlocation.aspx

The browser then initiates another request (assuming it supports redirects) to somewhere/newlocation.aspx loading its contents in the browser.

Anyway, if the response stream is buffered ("Hey") you are overwriting this response with Response.Redirect.

Upvotes: 2

Related Questions