I'm building a small ASPX page in C# to forward HTTP POST requests to
another site. When the other site returns an HTTP error such as 404 or
405, I want to return that same HTTP status value to my caller. But when
I do so, my caller always reports HTTP error 500. How can I return the
actual HTTP status that I received?
Here is my code:
private void Page_Load(object sender, System.EventArgs e)
{
bool failed = false; // No exceptions caught yet.
Exception copyOfException = null;
try {
string UrlForThisQuery = Global.NextServerUrl() + "BAD";
System.Net.WebClient client = new System.Net.WebClient();
byte [] byXmlOut = null;
if ( 0 == Request.Form.Count ) {
// First case: no parameters; this must be an HTTP GET.
// Perform an HTTP GET.
byXmlOut = client.DownloadData(UrlForThisQuery);
} else {
// Second (main) case: one or more parameters;
// this is a normal XML query in the form of HTTP POST.
// Just forward the POST.
byXmlOut = client.UploadValues(UrlForThisQuery,
Request.Form);
}
// Return the content of the page to the caller.
Response.BinaryWrite(byXmlOut);
}
catch (WebException ex) {
HttpWebResponse r = (HttpWebResponse)ex.Response;
copyOfException = new WebException(
ex.Message,
ex,
(WebExceptionStatus) r.StatusCode, // 404
ex.Response);
failed = true;
}
// Relay any exception to the caller.
if (failed) {
throw copyOfException; // But the caller reports 500.
}
// Normal exit. We already performed Response.BinaryWrite() above.
}
-- Phil Davidson, Oakland, CA