Skip to content

Instantly share code, notes, and snippets.

@StefanoChiodino
Last active January 28, 2021 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefanoChiodino/ad6f6860c235f4fd1d536fe53f887c2c to your computer and use it in GitHub Desktop.
Save StefanoChiodino/ad6f6860c235f4fd1d536fe53f887c2c to your computer and use it in GitHub Desktop.
Generate a static html error page from umbraco dynamic one to make it more resilient
public class ErrorPageGeneratorEventHandlers : ApplicationEventHandler
{
private static readonly object Lock = new object();
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
GenerateStaticErrorPage();
ContentService.Published += (sender, args) => GenerateStaticErrorPage();
ContentService.UnPublished += (sender, args) => GenerateStaticErrorPage();
}
private static async void GenerateStaticErrorPage()
{
var errorPage = UmbracoHelpers.GetAllNodesOfType<PageError>().FirstOrDefault();
if (errorPage == null)
{
return;
}
var errorPageAbsoluteUrl = errorPage.UrlAbsolute();
await GenerateStaticErrorPage(errorPageAbsoluteUrl);
}
private static async Task GenerateStaticErrorPage(string errorPageAbsoluteUrl)
{
try
{
var httpClient = new HttpClient();
var httpResponseMessage = await httpClient.GetAsync(errorPageAbsoluteUrl);
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
return;
}
var errorPageHtml = await httpResponseMessage.Content.ReadAsStringAsync();
var path = AppDomain.CurrentDomain.BaseDirectory
+ "error.html";
using (var streamWriter = new StreamWriter(path))
{
lock (Lock)
{
streamWriter.Write(errorPageHtml);
}
}
}
catch (Exception e)
{
LogHelper.Error(
typeof(ErrorPageGeneratorEventHandlers),
"Could write error page to file", e);
}
}
}
@Al-Sharif
Copy link

can you explain more?

@blachawk
Copy link

blachawk commented Feb 2, 2018

Yes please explain in detail what is going on through the code. Thanks

@StefanoChiodino
Copy link
Author

This event handler download a page error type as anything is published or unpublished, fetches it with an http client and saves it as "error.html". This way your editors can have a page that they edit the content for, all menus updates just like the rest of your site, but is more resilient than a dynamic page (something needs to be very broken for iis not to be able to server a static html file).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment