Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

Al-Sharif commented Jan 15, 2018

can you explain more?

@blachawk

This comment has been minimized.

Copy link

blachawk commented Feb 2, 2018

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

@StefanoChiodino

This comment has been minimized.

Copy link
Owner Author

StefanoChiodino commented Feb 7, 2019

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
You can’t perform that action at this time.