Get 404 Status Code from Custom Error Page.

Scenario

We had to figure out how many pages in our site are broken (throwing 404 status code). But the problem was that we implemented a custom designed error page for broken ones. This page was designed in the context of site look and feel, so we associated the site master
page as well with this customized error page. Due to this implementation, we never get the 404 status code as a broken page would redirect to 404 custom page and because this was an actual page with the master page; it always gave 200 OK.

Resolution

Override the render event of the page and force it to serve the error from IIS directly.

See below the code snippet.

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
Response.TrySkipIisCustomErrors = true; //Always get custom 404 page in place of default IIS 404 page.
Response.StatusCode = 404; //Set the status.
}