0

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.

if(Failed)
{
 Context.Response.TrySkipIisCustomErrors = true;

 Context.Response.ClearContent();

 Context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

 HttpContext.Current.ApplicationInstance.CompleteRequest();

 Context.Response.End();
}

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)

But when I place the entire code

 Context.Response.TrySkipIisCustomErrors = true;

 Context.Response.ClearContent();

 Context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

 HttpContext.Current.ApplicationInstance.CompleteRequest();

 Context.Response.End();

directly in PageLoad without any other code preceeding these lines, I get back the response code, this is weird.

I have also tried using HTTPModule but the same.

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.

But I do get the response content cleared.

NEVERMIND

Never mind.

There were two causes to this issue:

One was localhost didnt throw the required error for HTTPREquest status code and when deployed to a IIS Site on server, Everything looked good.

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.

All in all, the lines of code is great.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

I suggest you check that the variable "Failed" is set properly. For debugging purpose, just try changing the if condition to if(true)
I am guessing there may be issue with variable you are using in the conditional statement

testuser
  • 668
  • 10
  • 23