Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a Status Code 500 in ASP.Net and still write to the response?

I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

header("HTTP/1.1 500 Internal Server Error"); header("Content-Type: text/plain"); echo "Unable to connect to database on $dbHost"; 

The ASP.Net (C#) equivalent should be:

Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; Context.Response.ContentType = "text/plain"; Context.Response.Write("Unable to connect to database on " + dbHost); 

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

Thanks!

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.

like image 370
Neil E. Pearson Avatar asked Dec 21 '10 03:12

Neil E. Pearson


People also ask

What would a response status code of 500 be classified as?

The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from fulfilling the request. This error is usually returned by the server when no other error code is suitable.


1 Answers

Context.Response.TrySkipIisCustomErrors = true

like image 84
Neil E. Pearson Avatar answered Sep 26 '22 21:09

Neil E. Pearson