Setting StatusCode in error.aspx triggers another Page_Load() <p>In <code>web.config</code>, the error page is set to <code>/errorpages/error.aspx</code></p> <pre><code>&lt;httpErrors errorMode="Custom" existingResponse="Replace" &gt; &lt;remove statusCode="500" subStatusCode="-1" /&gt; &lt;error statusCode="500" path="/errorpages/error.aspx" responseMode="ExecuteURL" /&gt; &lt;/httpErrors&gt; </code></pre> <p>But when the page <code>/errorpages/error.aspx</code> is loaded in the browser, the status code is 200. This results in various problems, like the fact that when I have a JS file that's in the wrong URL, instead of getting a specific error, I get a JS error like <code>unexpected &lt;</code> (same logic is used for <code>404.aspx</code> page).</p> <p>So, to fix this, inside <code>error.aspx</code>, in <code>Page_Load()</code>, I set</p> <pre><code>Response.StatusCode = 500; </code></pre> <p>and the page is returned with 500 status code, which can be observed in the browser.</p> <p>The problem is that if I place a breakpoint inside <code>Page_Load()</code> in <code>/errorpages/error.aspx</code>, it is being hit twice. First time it enters the <code>StatusCode</code> is <code>200</code>, it sets it to <code>500</code>, so my suspicion is that IIS tries to handle that from <code>web.config</code>, it loads the page again. And again the <code>StatusCode</code> is <code>200</code>, and changes to <code>500</code>, but this time it doesn't trigger another execution.</p> <p>This is probably caused by the fact that the exceptions are being handled in Global.asax.cs, where after handling, this is executed:</p> <pre><code>Server.TransferRequest("/errorpages/error.aspx?someExceptionInfo=" + exceptionInfo); </code></pre> <p>So this diagram shows what I think is happening: <a href="https://i.stack.imgur.com/rmT2J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rmT2J.png" alt="error workflow"></a></p> <p>I <em>could</em> just set a status code instead of calling <code>TransferRequest</code>, and let IIS handle it, and pass the exception info via the Session. But I'm worried that at some point it might cause some kind of redirect loop or something on Production servers.</p> <p><strong>Question (one of them):</strong></p> <ul> <li>How do I ensure I won't get a redirect loop?</li> <li>How do I configure IIS to make error pages return a status code without actually writing <code>Response.StatusCode = ***</code>?</li> <li>How do I impede my application from repeating execution of the page when I set the <code>StatusCode</code>?</li> </ul>