Short Version:
If I create a System.Web.HttpException as follows:
var exception = new HttpException(403, "Forbidden");
I would expect the following methods to return these values, but they don’t:
var code = exception.GetHttpCode(); // is 0
var msg = exception.GetHtmlErrorMessage(); // is: null
Edit: In fact GetHttpCode() returns the correct number when being called the first time, but returns 0 when being called a second time:
var code = exception.GetHttpCode(); // is 403
code = exception.GetHttpCode(); // is 0
Long Version:
I am trying to unit-test the ASP.NET global exception handling method “Application_Error”. This is an extract of the code:
var httpException = server.GetLastError() as HttpException;
if (httpException != null)
{
response.StatusCode = httpException.GetHttpCode();
response.StatusDescription = httpException.GetHtmlErrorMessage();
// ...
The unit test calls this method with a mock ServerUtilityBase object (Moq) which returns an HttpException when server.GetLastError() is called:
var exception = new HttpException(403, "Forbidden");
serverMock.Setup(server => server.GetLastError()).Returns(exception);
// ...
Unfortunately I had to find out that in the error handling code, httpException.GetHttpCode() and httpException.GetHtmlErrorMessage() methods return 0 or null, respectively.
What needs to be done to make a new HttpException(403, "Forbidden") return 403 or "Forbidden" when calling these methods?
Unfortunately it is not possible to create a Mock of the exception by subclassing it, because the said methods are sealed.
The httpException.GetHtmlErrorMessage() method is used to return the html which is sent to the browser by the ASP.NET Runtime, Patrick is correct in that you need to look at the .Message property to see the text “forbidden”. If you want to see what the actual html looks like, you would need to supply an inner exception which is an exception type that the ErrorFormatter can use (for example a SecurityException).
will output: