Note to Self - Generating HTTP 500 Internal Server Error Custom Response


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:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language:
en-us,en;q=0.5

Accept-Encoding:
gzip,deflate

Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive:
300

Connection:
keep-alive

Referer:
http://localhost:17109/HTTP500Test/Service.asmx?op=ThrowHTTPException

Content-Type:
application/x-www-form-urlencoded

Content-Length:
0

 

HTTP/1.x 500
Internal Server Error

Server:
ASP.NET Development Server/9.0.0.0

Date: Fri, 30
May 2008 15:58:24 GMT

X-AspNet-Version:
2.0.50727

Cache-Control:
private

Content-Type:
text/plain; charset=utf-8

Content-Length: 152

Connection:
Close

Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language:
en-us,en;q=0.5

Accept-Encoding:
gzip,deflate

Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive:
300

Connection:
keep-alive

Referer: http://localhost:17109/HTTP500Test/Service.asmx?op=ResponseHeader500Error

Content-Type:
application/x-www-form-urlencoded

Content-Length:
0

 

HTTP/1.x 500
Internal Server Error

Server:
ASP.NET Development Server/9.0.0.0

Date: Fri, 30
May 2008 15:57:10 GMT

X-AspNet-Version:
2.0.50727

Cache-Control:
private, max-age=0

Content-Length:
0

Connection:
Close

 

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)

Share