title: Http Response Code programmatically
body: <p>Based on the condition, I want to send a 400 (infact any code other than 200(Status OK)) error code back from my Asp.net page.</p>
  
  <pre><code>if(Failed)
  {
   Context.Response.TrySkipIisCustomErrors = true;
  
   Context.Response.ClearContent();
  
   Context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
  
   HttpContext.Current.ApplicationInstance.CompleteRequest();
  
   Context.Response.End();
  }
  </code></pre>
  
  <p>I have this code in PageLoad method. But unfortunately this does not work if I have the If statement above (And yes the code inside the If statement is executed, seen this in debugging)</p>
  
  <p>But when I place the entire code </p>
  
  <pre><code> Context.Response.TrySkipIisCustomErrors = true;
  
   Context.Response.ClearContent();
  
   Context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
  
   HttpContext.Current.ApplicationInstance.CompleteRequest();
  
   Context.Response.End();
  </code></pre>
  
  <p>directly in PageLoad without any other code preceeding these lines, I get back the response code, this is weird.</p>
  
  <p>I have also tried using HTTPModule but the same. </p>
  
  <p>I am not understanding why when any other line of code is executed prior to setting response code then the response is not set, has any one faced this.</p>
  
  <p>But I do get the response content cleared.</p>
  
  <p><strong>NEVERMIND</strong></p>
  
  <p>Never mind.</p>
  
  <p>There were two causes to this issue:</p>
  
  <p>One was localhost didnt throw the required error for HTTPREquest status code and when deployed to a IIS Site on server, Everything looked good.</p>
  
  <p>Second was I was automating the test to check programatically using HttpWebRequest. And to the request object I had forgotten to send the request header information as I am making decision based on request headers.</p>
  
  <p>All in all, the lines of code is great.</p>