Last active
January 28, 2021 19:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Yes please explain in detail what is going on through the code. Thanks
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
can you explain more?