Returning HTTP 500 internal server error as your web service
/ asp.net REST responses in case of failures may sound like an odd idea but it has its merits; with handlers and load balancing
environments where you want your intelligent routing devices to redirect request to a
different server based on an HTTP header response, this approach can come in handy.
In order to return an HTTP 500 server error custom response,
there are two simple ways to achieve it.
By throwing an HTTP exception
throw new System.Web.HttpException(500,
"Internal Server Error");
Or by modifying the headers.
HttpContext.Current.Response.Status = "500 Internal Server Error";
HttpContext.Current.Response.AddHeader("Status Code", "500");
HttpContext.Current.Response.End();
Looking at the response from the HTTP headers, they are
almost identical. The only difference is that due to termination of response
stream in the later case, the content length is 0.
Accept: Accept-Language: Accept-Encoding: Accept-Charset: Keep-Alive: Connection: Referer: Content-Type: Content-Length: HTTP/1.x 500 Server: Date: Fri, 30 X-AspNet-Version: Cache-Control: Content-Type: Content-Length: 152 Connection: |
Accept: Accept-Language: Accept-Encoding: Accept-Charset: Keep-Alive: Connection: Referer: http://localhost:17109/HTTP500Test/Service.asmx?op=ResponseHeader500Error Content-Type: Content-Length: HTTP/1.x 500 Server: Date: Fri, 30 X-AspNet-Version: Cache-Control: Content-Length: Connection: |
The similar result can be achieved by throwing an ApplicationException
or custom exception as well because for the runtime, it still means an internal
server error.
The source for the web service project can be downloaded from here. HTTP500Test-Src.zip (2.79 KB)