I'm trying to create dynamic custom web-form error page where content changes according to the status code. I have configured httpErrors in web.config like this:
<httpErrors errorMode="Custom" defaultPath="\errorpages\ErrorPage.aspx" defaultResponseMode="ExecuteURL" existingResponse="Auto" allowAbsolutePathsWhenDelegated="true" >
<remove statusCode="503" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<remove statusCode="401" subStatusCode="-1" />
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="503" responseMode="ExecuteURL" path="/errorpages/ErrorPage.aspx" />
<error statusCode="500" responseMode="ExecuteURL" path="/errorpages/ErrorPage.aspx" />
<error statusCode="401" responseMode="ExecuteURL" path="/errorpages/ErrorPage.aspx" />
<error statusCode="404" responseMode="ExecuteURL" path="/errorpages/ErrorPage.aspx" />
</httpErrors>
QUESTION: How can I get the status code in code behind file before the page renders so it changes the content depending on the status code?
I wish to have 1 file for all the errors and not 4 different files.
I tried to use Server.GetLastError(), but it's always null whether I put it in Global.asax Page_Error(object sender, EventArgs e) method or code behind file.
You could add a QueryString with the status code and handle that on the error page to show the correct contents. So first add the code as Querystring
<error statusCode="404" path="/errorpages/ErrorPage.aspx?code=404" />
Then the ErrorPage.aspx page you can do something like this
<%@ Page Language="C#" %>
<script runat="server">
int error = 0;
string errorname = "";
protected void Page_Load(object sender, EventArgs e)
{
//check if there is a code
if (Request.QueryString["code"] != null)
{
//is the code a correct number
int.TryParse(Request.QueryString["code"], out error);
}
if (error == 403)
{
errorname = error + " Forbidden";
}
else if (error == 404)
{
errorname = error + " Not Found";
}
else if (error == 500)
{
errorname = error + " Server Error";
}
else
{
errorname = "Unhandled Error";
error = 500;
}
}
</script>
<html>
<head>
<title>MySiteName - <%= errorname %></title>
</head>
<body>
<center>
<a href="/">
<img src="/images/<%= error %>.png" border="0" vspace="50">
</a>
</center>
</body>
</html>