Skip to content

Instantly share code, notes, and snippets.

@hardye
Forked from timw255/Global.asax.cs
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hardye/1524ab046c9ad470d37e to your computer and use it in GitHub Desktop.
Save hardye/1524ab046c9ad470d37e to your computer and use it in GitHub Desktop.
protected void Application_Error(object sender, EventArgs e)
{
// get the last error
HttpException err = Server.GetLastError() as HttpException;
Server.ClearError();
// try to skip using any other custom error settings
Response.TrySkipIisCustomErrors = true;
// we're on!
if (err != null)
{
// get the language from the visitor's browser settings
string lang = (Request.UserLanguages ?? Enumerable.Empty<string>()).FirstOrDefault();
var culture = CultureInfo.GetCultureInfo(lang);
// set the culture to match the browser language
Thread.CurrentThread.CurrentUICulture = culture;
PageManager pageManager = PageManager.GetManager();
PageNode pNode = null;
// this is where we would put a manager to do some fancy lookups based on the error codes & user selections
switch (err.GetHttpCode())
{
case 404:
pNode = pageManager.GetPageNodes().Where(pN => pN.Title == "404").FirstOrDefault();
break;
case 500:
default:
pNode = pageManager.GetPageNodes().Where(pN => pN.Title == "Generic").FirstOrDefault();
break;
}
// grab the URL of the error page we're going to display to the visitor
string url = pNode.GetFullUrl(culture, true);
url = UrlPath.ResolveUrl(url, true, true);
// make a web request to the URL and grab the entire HTML of the page
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
// send back the error page and correct status code
Response.Write(html);
Response.StatusCode = err.GetHttpCode();
}
}
<customErrors mode="On">
<error statusCode="404" redirect="~/8ec96125-02ce-47e2-a545-0eba4192dc7d" />
</customErrors>
<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="/CustomErrorPages/8ec96125-02ce-47e2-a545-0eba4192dc7d.aspx" responseMode="ExecuteURL" />
</httpErrors>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment